2010-08-24 149 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> 

在我看來這種模式允許你用更大的靈活性風景。

相關問題