动作控制器简介
为使用 例如,你的类如下定义:
class FooController extends Zend_Controller_Action
{
public function barAction()
{
// do something
}
public function bazAction()
{
// do something
}
}
上述 还有更多的可以被实现,例如定制初始化动作,如果没有动作(或者有个无效动作)被指定,缺省的动作被调用,派遣之前和之后的钩子,以及无数的助手方法。这章是动作控制器功能的一个总览。
对象初始化
虽然你可以总重写动作控制器的构造函数,我们不建议这么做。Zend_Controller_Action::__construct()执行一些重要的任务,如注册请求和响应对象,还有任何从前端控制器传来的invocation参数。如果你必须重写构造函数,别忘记调用
更合适的方法来定制实例化是使用
class FooController extends Zend_Controller_Action
{
public function init()
{
$this->db = Zend_Db::factory('Pdo_Mysql', array(
'host' => 'myhost',
'username' => 'user',
'password' => 'XXXXXXX',
'dbname' => 'website'
));
}
}
派遣前后的钩子
访问器无数的对象和变量与对象一起注册,并且每个都有访问器方法。
视图集成
视图初始化
缺省的实现使用下面假设的目录结构:
applicationOrModule/
controllers/
IndexController.php
views/
scripts/
index/
index.phtml
helpers/
filters/
换句话说,视图脚本假定放在 解析(Rendering)视图
string render(string $action = null,
string $name = null,
bool $noController = false);
一些例子:
class MyController extends Zend_Controller_Action
{
public function fooAction()
{
// Renders my/foo.phtml
$this->render();
// Renders my/bar.phtml
$this->render('bar');
// Renders baz.phtml
$this->render('baz', null, true);
// Renders my/login.phtml to the 'form' segment of the
// response object
$this->render('login', 'form');
// Renders site.phtml to the 'page' segment of the response
// object; does not use the 'my/' subirectory
$this->render('site', 'page', true);
}
public function bazBatAction()
{
// Renders my/baz-bat.phtml
$this->render();
}
}
实用方法
除了访问器和视图继承方法,在动作方法内部里,
继承(Subclassing)动作控制器
为了创建动作控制器,设计上,
除了为web应用程序创建有用的函数外,你可能发现在不同的控制器里重复同样的设置和实用方法;如果这样,创建一个继承(extends) Example #1 如何处理不存在的动作
如果控制器的请求包括一个未定义的动作方法,
缺省地,这个方法抛出一个 如果想执行其它操作,你应该重写这个函数。例如,如果你想显示错误信息,可以象下面这样来写:
class MyController extends Zend_Controller_Action
{
public function __call($method, $args)
{
if ('Action' == substr($method, -6)) {
// If the action method was not found, render the error
// template
return $this->render('error');
}
// all other methods throw an exception
throw new Exception('Invalid method "'
. $method
. '" called',
500);
}
}
另外的可能性就是你可能想转发到缺省控制页面:
class MyController extends Zend_Controller_Action
{
public function indexAction()
{
$this->render();
}
public function __call($method, $args)
{
if ('Action' == substr($method, -6)) {
// If the action method was not found, forward to the
// index action
return $this->_forward('index');
}
// all other methods throw an exception
throw new Exception('Invalid method "'
. $method
. '" called',
500);
}
}
为了定制控制器,除了重写
abstract class My_Base_Controller extends Zend_Controller_Action
{
public function initView()
{
if (null === $this->view) {
if (Zend_Registry::isRegistered('view')) {
$this->view = Zend_Registry::get('view');
} else {
$this->view = new Zend_View();
$this->view->setBasePath(dirname(__FILE__) . '/../views');
}
}
return $this->view;
}
}
很希望你能从这章的信息里发现这个特别的组件的灵活性并且用到你的程序和网站里。
|