【问题标题】:how to use your own functions and/or classes in Zend Framework?如何在 Zend Framework 中使用自己的函数和/或类?
【发布时间】:2013-12-11 18:04:12
【问题描述】:


自从我开始编码以来,我一直在创建我的一组函数,我想在 Zend Framework 1.12 的整个项目中使用这些函数
我知道我可以放置在我将在库中创建的文件夹中,但是我正在寻找一种不同的方式来使用我的功能。
如果我把我的功能放在:

.../library/myfunctionsfolder/myfunctions.php

当我需要使用此文件中的任何功能时,我必须在每个控制器中包含此文件。
但是,我正在寻找一种方法,可以直接从任何控制器中的文件调用函数,而无需包含该文件。
例如:

my_function($some_var);

我应该在 Zend_Controller 中包含这个文件还是一个坏主意?
我该怎么做?
感谢您的帮助

【问题讨论】:

  • 这个答案也适用于 ZF1:stackoverflow.com/questions/4737199/…
  • step2(预加载)你可以在 Bootstrap.php 中做。
  • @redreggae 我怎么能使用预加载,你能发布一个例子吗?它能让我使用我描述的功能吗?

标签: php function class zend-framework


【解决方案1】:

就像我说的,以下几点对 ZF1 都有效:Autoloader for functions

如果你真的喜欢使用函数并想预加载它们,那么最好的地方是 Bootstrap.php。

所以在Application\Bootstrap.php 中创建一个带有前缀_init 的新方法:

protected function _initPreloading()
{
    include LIBRARY_PATH."/myfunctionsfolder/myfunctions.php";
    include LIBRARY_PATH."/myfunctionsfolder/myfunctions2.php";
}
/* For those who does not know how to address the library (in case you cannot use LIBRARY_PATH) You can use this:
include ( APPLICATION_PATH . '/../library/Customfunctions/functions.php'); */

为此,您需要在 application.ini 中添加以下 2 行:

bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"

更新:

要使用LIBRARY_PATH,我在 index.php 中包含以下内容:

// Define path to library directory
defined('LIBRARY_PATH') 
    || define('LIBRARY_PATH', realpath(dirname(__FILE__) . '/../library'));

有关引导的更多信息:Bootstrapping

另一种方法是使用控制器插件进行条件预加载。如果您只需要控制器中的某些功能。

更多关于如何编写插件的信息:Plugins

【讨论】:

  • 这样的情况下我如何从文件中调用函数?
  • 只要调用它;)如果包含文件,您可以从任何地方调用函数..
  • 如果你在 Bootstrap.php 中包含该文件,它可以在任何地方使用
  • woo hoo :) 我在处理库文件夹时遇到了问题。现在无论我在哪里调用它都在工作的功能。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
相关资源
最近更新 更多