Overriding Zend_Controller_Action
Extending Zend_Controller_Action can help make your app consistent and save you lots of coding down the road.
You certainly want at least:
- An init hook.
- An authentication hook.
- A way to define the model or models being used.
So here is a basic "base" controller you could use in your apps.
<?php
class PaloVerde_Controller_Base extends Zend_Controller_Action {
/**
* Init model names
*/
/**
*@var string If there is only one model, enter it's class name
*/
public $modelName = null;
/**
*@var array If there are multiple models, make an assoc. array of varName=>className
*/
public $modelNames = null;
/**
*@var Doctrine_Record The loaded model
*/
public $model = null;
/**
*@var stdObj An Object containing the loaded models defined in self::modelNames
*/
public $models = null;
/**
* Override the Zend_Controller_Action::init() for our own functionality
*/
public function init() {
// Do any authentication that needs to be done, this is defined by a child class
$this->doAuth();
// Restore our user from session information
$this->restoreUser();
// Run a setup function, defined by child classes
$this->setUp();
// Load any database models
$this->loadModels();
}
/**
* Load our user from session information, if it exists.
*/
public function restoreUser() {
if (Zend_Auth::getInstance()->hasIdentity()) {
$this->user = Doctrine::getTable('Users')->findOneByName(Zend_Auth::getInstance()->getIdentity());
}
}
/**
* Redirect to the login screen if authentication fails.
*/
public function showLogin() {
$this->_redirect(
$this->view->url(
array(
'module'=>'default',
'action'=>'in',
'controller'=>'authenticate'
)
)."?redirect=".urlencode($_SERVER['REQUEST_URI'])
);
}
/**
* Redirect to the site dashboard.
*/
public function showDashboard() {
$this->_redirect(
$this->view->url(
array(
'module'=>'default',
'action'=>'index',
'controller'=>'dashboard'
)
)
);
}
/**
* Load the models based on the information in self::modelName or self::modelNames or both
*/
public function loadModels() {
if (is_array($this->modelNames) and count($this->modelNames)) {
foreach ($this->modelNames as $key=>$val) {
$this->models = (object) null;
$this->models->$key = Doctrine::getTable($val);
}
}
if ($this->modelName) {
$this->model = Doctrine::getTable($this->modelName);
}
}
/**
* Custom auth method to be overridden by a child class
*/
public function doAuth(){}
/**
* Custom setup method to be overridden by a child class
*/
public function setUp() {}
}
?>
0 comments