实现像 ZendFramework 这样有效的控制器/视图关联
我正在制作自己的 PHP-MVC 框架。我有一个关于控制器和视图关联的问题。 我喜欢 Zend 框架在控制器中使用视图的方式,如下所示:
$this->view->data = 'Data here';
因此它可以在视图中使用,如下所示:
echo $this->data;
我想知道如何实现这种关联。 我想删除 /** **/
之间的代码并想用一些神奇的函数替换。我的控制器代码如下:
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(){
}
public function forgotPassword(){
}
}
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(){
}
public function forgotPassword(){
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您实际上并不需要魔术函数来实现这一点。您可以这样做:
在控制器中创建一个名为
set
或assign
的方法,该方法采用名称和值并将其存储在数组中。在调用 view 之前,循环遍历该数组并分配给您的视图对象:You don't really need magic functions to implement this. You can just do:
Create a method in your controller called
set
orassign
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:使用魔术方法 __set() 和 __get()。
受保护的$_data = array();
然后在检索未设置的值等时实现错误处理...
Use the magic method __set() and __get().
protected $_data = array();
Then implement error handling when retrieving values which are not set, etc...