一直听人说PHP的框架框架,今天终于搞了一个下来试用了一下。由于本人一直面向过程编程经验较多,而且也没啥特别大(N万行以上)的代码开发经验,所以还觉得蛮别扭的。
首先,下载了网上的入门教程:Zend Framework 入门教程(简体中文版),以及其中的例子。然后在其基础上进行了一番试用和改写。
代码结构如下:
[chengyi@localhost zf-tutorial-01]$ ls
application library public tags
[chengyi@localhost zf-tutorial-01]$ ls application/ public/ -r
public/:
two.php js index.php images css
application/:
views models layouts controllers
要把代码运行起来,需要进行以下配置:
1、修改http.conf:允许.htaccess,可以通过AllowOverride None改写为AllowOverride All。
2、配虚拟host:
<VirtualHost *:80>
ServerName zf.centos.cn
DocumentRoot "/ms/wwwroot/zf-tutorial-01/public/"
DirectoryIndex index.php index.htm index.html
ErrorLog "logs/zf.error_log"
CustomLog "logs/zf.access_log" common
</VirtualHost>
3、重启apache
4、下载ZendFramework源码,解压:
[chengyi@localhost ZendFramework-1.8.4]$ ls
bin INSTALL.txt library LICENSE.txt README.txt
将ZendFramework-1.8.4/library/Zend下的内容全部cp到zf-tutorial-01/library/Zend下。
那么这个时候,我们还需要修改我们客户端机器上的host,配zf.centos.cn。
再看public和views、controls下的代码结构,来猜猜看我们可以通过什么url访问:
[chengyi@localhost zf-tutorial-01]$ ls public/
css images index.php js two.php
[chengyi@localhost zf-tutorial-01]$ ls application/views/scripts/ -R
application/views/scripts/:
index two
application/views/scripts/index:
add.phtml cytest.phtml delete.phtml edit.phtml index.phtml
application/views/scripts/two:
index.phtml
[chengyi@localhost zf-tutorial-01]$ ls application/controllers/
IndexController.php TwoController.php
其中index相关的是原有的,two相关的是我新增的。那么猜测,我们可以通过http://zf.centos.cn/index/edit 或者 http://zf.centos.cn/two/index 类似的url访问!
所以也就是说,如果我们要新增模块的话,比如two模块,那么就在public下添加two.php,在views下面添加two目录,下面包含每个phtml的页面。并且在controllers下面添加对应的TwoController.php。
这时,来看看index.php和IndexController.php都藏了是还没玄机呢?
index.php:
// 设置控制器
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory('../application/controllers');
Zend_Layout::startMvc(array('layoutPath'=>'../application/layouts'));
// run!
$frontController->dispatch();
这里设置了controllers和layouts的路径,然后zend framework会根据命名规则,去这些目录下面找到对应的文件。然后就是dispatch执行了。
IndexController.php:
class IndexController extends Zend_Controller_Action
{
function indexAction()
{
$this->view->title = "My Albums";
$this->_helper->layout->setLayout('two_layout'); // 改写layout,从layout.phtml到two_layout.phtml
//$this->_helper->layout->disableLayout(); // 禁用layout
}
... ...
}
也就是说,其实index.php起到一个dispatch的作用,根据规定的命名规范,将url映射到不同的action函数,view页面,layout中去。
当然,这只是zend framework的mvc框架部分而已。它其他强大的功能我还没用到。
对于一次请求来说,处理流程是这样的:
url request(http://zf.centos.cn/index/edit)--> index.php --> IndexController.php --> editAction() -->
if need layout --> layout --> $this->layout()->content 输出view内容等 --> over
else --> view --> over