前端控制器是MVC組建中的苦力,因為它要實例化對象、觸發事件、建立默認的行為等,它的主要目的是處理所有進入應用的請求。前端控制器的設計模式被應用於不同的MVC框架中,我們在Zend Framework中指代的前端控制器(Front Controller)實際上是指Zend_Controller_Front類,因為該類實現了前端控制器的模式;另一定注意的是,前端控制器設計是單例模式(Singleton),這也就意味著它實現了單例設計模式,也就是僅僅只能有一個實例化的前端控制器,即我們不能直接實例化Front Controller,而是拿取一個。
下面我們實現一個簡單的controller跳轉與分發。
在controllers文件夾裡建立了IndexController.php,還有在view文件夾裡建立了index.phtml 文件,在地址欄輸入http://localhost/NowaMagicFrame1.0/可以浏覽。
<?php
require('CommonController.php');
class IndexController extends Zend_Controller_Action
{
function init()
{
//parent::init();
$this->registry = Zend_Registry::getInstance();
$this->view = $this->registry['view'];
$this->view->baseUrl = $this->_request->getBaseUrl();
}
public function indexAction()
{
//這裡給變量賦值,在index.phtml模板裡顯示
$this->view->bodyTitle = 'NowaMagic Frame 1.0';
echo $this->view->render('index.phtml');//顯示模版
}
/**
* 新聞
*
*/
public function newsAction(){
//這裡給變量賦值,在news.phtml模板裡顯示
$this->view->bodyTitle = 'NowaMagic Frame 新聞';
echo $this->view->render('news.phtml');//顯示模版
}
}
?>
現在我想訪問news頁面,就可以通過IndexContriller來訪問了,因為它裡面有newsAction()這個方法可以實現轉發。具體訪問方式為http://localhost/NowaMagicFrame1.0/index/news/
但是這個URL看起來並不如想象中好,比較理想的URL看起來應該這樣:http://localhost/NowaMagicFrame1.0/news/
怎麼實現呢?我們需要建立一個NewsController.php
<?php
class NewsController extends Zend_Controller_Action
{
function init()
{
$this->registry = Zend_Registry::getInstance();
$this->view = $this->registry['view'];
$this->view->baseUrl = $this->_request->getBaseUrl();
}
/**
* 標簽首頁
*
*/
function indexAction(){
echo $this->view->render('news.phtml');
}
}
?>
在這個文件中加個indexAction即可。