如何在 zend 控制器中自动加载单例类(私有构造函数)?
我的模型目录中有一个单例类,我必须在控制器类中使用它的函数。通过 require_once('file path'); 执行此操作并将函数调用为 ClassName::FunctionName() 工作正常,但我需要使用 Zend Autoloader 而不是通过 require_once 包含类。我在 stackoverflow 上遇到了许多解决方案,这些解决方案使用 bootstrap.php 来添加以下代码,看起来与 require_once('file path'); 的做法相同。在控制器中
protected function _initAutoload()
{
Zend_Loader_Autoloader::getInstance();
}
这样做,这样我得到致命错误:Class 'ClassName' not found in {path}\controllers\SampleController.php on {line no.} 我确信我错过了一些东西,但无法弄清楚到底是什么。
I have a singleton class in my models directory and I have to use its function in Controller class. Doing it by require_once('file path'); and calling function as ClassName::FunctionName() works fine, but I need to use Zend Autoloader instead of including class through require_once. I came across number of solutions here on stackoverflow which used bootstrap.php in terms of adding following code there and it seems like doing the same as require_once('file path'); did in controller
protected function _initAutoload()
{
Zend_Loader_Autoloader::getInstance();
}
Going this way I get Fatal error: Class 'ClassName' not found in {path}\controllers\SampleController.php on {line no.}
I am sure I am missing something but cant figure out what exactly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 user1145086 所说,如果您遵循 Zend 的命名约定,您的类应该会自动加载。
如果您有一个类,例如 AutoloadedClass,并且希望它自动加载,则可以执行以下操作:
在 Bootstrap 的 initAutoload 类方法中编写以下代码:
Like user1145086 has rightly said, if you follow the naming convention of Zend, you class should be auto-loaded.
If you have a class, say AutoloadedClass, and you want it auto-loaded, you can do the following:
Write the following code in your Bootstrap's initAutoload class method:
如果您根据 zend 约定命名您的类,则该类应该自动加载而不会出现问题。
如果您的类位于 /application/models/myClass.php 并命名为:
它应该可以很好地自动加载,我认为单例这一事实不会影响自动加载。
如果您需要使用自己的类名,您可以将新的命名空间添加到 /library 目录中的自动加载器中,将此行添加到您的 application.ini 中:
然后将 /MyNamespace 目录添加到 /library 目录中,并相应地命名您的文件:
希望这会有所帮助。
if you name your class according to zend conventions, the class should autoload without problem.
If your class is located at /application/models/myClass.php and is named :
it should autoload just fine, I don't think the fact that is a singleton would affect autoloading.
If you need to use your own class names you can add a new namespace to the autoloader the works in the /library directory, add this line to your application.ini :
then add the /MyNamespace directory to the /library directory and name your files accordingly:
Hope this helps.
如果库中的类名称和位置不遵循 Zend 命名约定,然后您可以为该库编写一个自动加载器,并将该自动加载器推送到
Zend_Loader_Autoloader
堆栈上。有关示例,请参阅 https://stackoverflow.com/a/8820536/131824。
If class names and locations in your library do not follow Zend naming conventions, then you can write an autoloader for that library and push this autoloader onto the
Zend_Loader_Autoloader
stack.See https://stackoverflow.com/a/8820536/131824 for an example.