ZF 1.8引导模块 - ZF Dream
ZF 1.8引导模块
我已经开始尝试用Zend Framework 1.8里的模块,新的自动加载功能让你所有的模型目录不在include_path里也能被自动加载。我特别感兴趣的是现在能在一个模块中实例化另一个模块的模型。
建立所有模块不难,但我觉得说简单明了不容易,所以我加了标注。
首先用ZF命令行来创建一个ZF项目:
不要忘记复制ZF 1.8到library目录,或着它在include_path中也行。
我们现在来创建模块:
$ zf create module blog
这会在myproject/application/modules/blog中创建所有相关的目录。接下来,我们在blog模块中建立一个简单的模型:
文件:myproject/application/modules/blog/models/Info.php
<?php class Blog_Model_Info { public function getInfo() { return "This is the info about the Blog module"; } }
名字的写法很重要:必须先是模块名,然后是单词“Model”,最后是模型本身的名字。注意模型名必须和模型的文件名一致! (ZF Dream翻译)
我们在index controller和index action下调用这个模型,代码如下:
文件:myproject/application/controller/IndexController.php
<?php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { // action body $info = new Blog_Model_Info(); $this->view->blogInfo = $info->getInfo(); } }
我已经在这里写了整个类,它大部分是自动生成的,你只需在//action body提示下加两个新行,然后传递一些内容到视图。我们要输出内容,那样才知道是否写对了:
文件: myproject/application/views/scripts/index/index.phtml
<?php echo $this->blogInfo; ?>
(注意我们替换了漂亮的ZF欢迎页。)(ZF Dream翻译)
这里报错了:
这是因为我们还没有告诉自动加载类我们要加载的模型所在模块在哪个目录。这可以用Zend_Application的引导文件来做,分为两步:
第一步,在application.ini里在[production]的尾部加一行代码来启用模块:
文件:myproject/application/configs/application.ini
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules" resources.modules[] = ""
第二部,给我们的模块增加一个引导文件:
文件:myproject/application/modules/blog/Bootstrap.php
<?php class Blog_Bootstrap extends Zend_Application_Module_Bootstrap { }
同样,名字的写法很重要。类名必须是{module name}_Bootstrap这样,必须扩展Zend_Application_Module_Bootstrap。这个引导文件要保存在模块的根目录,名为Bootstrap.php。(ZF Dream翻译)
就这样,如果你刷新页面,你就能看到Blog模块的数据了,信息是用默认模块来显示的:
总得来说,这没啥难的。记住如果你没有在application.ini写那两行,并且定义模块引导文件的位置,那它就跑不起来。(ZF Dream翻译)
原文:http://akrabat.com/2009/07/08/bootstrapping-modules-in-zf-1-8(Rob Allen)