2010-08-24 148 views
5

我正在创建我自己的非常简单的MVC,我正在集思广益的方式从控制器到视图。这涉及将变量从一个类发送到普通的旧PHP页面。从控制器到视图

我相信这已经被覆盖过,但我想看看人们可以提出什么样的想法。

//this file would be /controller/my_controller.php 

class My_Controller{ 

    function someFunction(){ 

    $var = 'Hello World'; 
    //how do we get var to our view file in the document root? 
    //cool_view.php 

    } 

} 

回答

1

某种散列表是一种很好的方法。将您的变量作为关联数组返回,这将填充视图中的所有空白。

+0

所以你建议只返回控制器中的变量。然后在视图中说$ vars = new my_controller();然后使用适当的功能。这确实是一个很好的简单解决方案。 – Mike 2010-08-24 22:25:52

1

Store中的变量在你的控制器对象的属性,然后在渲染

class My_Controller { 

    protected $locals = array(); 

    function index() { 
     $this->locals['var'] = 'Hello World'; 
    } 

    protected function render() { 
     ob_start(); 
     extract($this->locals); 
     include 'YOUR_VIEW_FILE.php'; 
     return ob_get_clean(); 
    } 
} 

时提取它们可以定义那些神奇的__get和__set方法,使其更漂亮

$this->var = 'test'; 
+0

使用'extract'时要小心,使用前请仔细阅读http://ru2.php.net/manual/en/function.extract.php – Kirzilla 2010-08-24 22:28:59

1

我也开发我自己的简单的MVC和most simple way这样做是...

class My_Controller 
{ 

    function someFunction() { 
     $view_vars['name'] = 'John'; 
     $view = new View('template_filename.php', $view_vars); 
    } 

} 

View类

class View 
{ 
    public function __construct($template, $vars) { 
     include($template); 
    } 
} 

template_filename.php

Hello, <?php echo $vars['name'];?> 

我强烈建议你看看PHP萨文特http://phpsavant.com/docs/

0

我创建了自己的MVC的免费PHP当然,我进行对于想要在PHP中变得更好的少数人来说。

到目前为止,最好的方法是使用Command + Factory模式。

E.g.

interface ControllerCommand 
{ 
    public function execute($action); 
} 

在每个控制器:

class UserController implements ControllerCommand 
{ 
    public function execute($action) 
    { 
     if ($action == 'login') 
     { 
      $data['view_file'] = 'views/home.tpl.php'; 
     } 
     else if ($action == 'edit_profile') 
     { 
      $data['view_file'] = 'views/profile.tpl.php'; 
      $data['registration_status'] = $this->editProfile(); 
     } 

     return $data; 
    } 
} 

从你的主前端控制器:

$data = ControllerCommandFactory::execute($action); 
if (!is_null($data)) { extract($data); } 
/* We know the view_file is safe, since we explicitly set it above. */ 
require $view_file; 

的一点是,每Controllercommand类有一个执行功能和返回其视图和任何数据为此观点。

对于完整的MVC,您可以通过在theodore [at] phpexperts.pro上给我发邮件来访问开源应用程序。

1

我想结账Zend_View以及它如何完成视图渲染。

你可以得到的ViewAbstractView源在github - unfortunaly我不觉得目前的资料库(在SVN)是易于浏览。

实质上,视图变量包含在一个View对象(您的控制器可以访问)中,然后模板(普通的旧php文档)在该对象内呈现。该方法允许模板访问$this

这将是这样的:

<?php 
class View 
{ 
    public function render() 
    { 
    ob_start(); 
    include($this->_viewTemplate); //the included file can now access $this 
    return ob_get_clean(); 
    } 
} 
?> 

所以在你的控制器:

<?php 
class Controller 
{ 
    public function someAction() 
    { 
    $this->view->something = 'somevalue'; 
    } 
} 
?> 

而且你的模板:

<p><?php echo $this->something;?></p> 

在我看来这种模式允许你用更大的灵活性风景。

相关问题