Implementing an effective Controller/View Association like ZendFramework
I am making my own PHP-MVC framework. i have a question regarding Controller and View Association. I love the way Zend framework uses view within Controller as follow:
$this->view->data = 'Data here';
so it can be used in view as follow:
echo $this->data;
I am wondering how can i implement this association.
I want to remove codes between /** **/
and want to replace with some magic functions. My codes for controller as as follow:
class UserController extends Controller{
/************************************/
public function __construct(){
$this->view = new View();
$this->view->setLayout( 'home' );
}
function __destruct(){
$this->view->render();
}
/************************************/
public function index(){
$this->redirect('user/login');
}
public function login(){
}
public function register(){
}
pub开发者_如何学运维lic function forgotPassword(){
}
}
You don't really need magic functions to implement this. You can just do:
$this->view->var1 = 'val1';
Create a method in your controller called set
or assign
that takes a name and value and store in an array. Before you call view, loop through that array and assign to your view object:
foreach ($this->viewVars as $viewVar) {
$this->view->$viewVar['name'] = $viewVar['val'];
}
Use the magic method __set() and __get().
protected $_data = array();
public function __set($name, $value)
{
$this->_data[$name] = $value;
}
public function __get($name)
{
return $this->_data[$name];
}
Then implement error handling when retrieving values which are not set, etc...
精彩评论