2013-03-30 136 views
3

隱藏視圖我想從我的Controller_Template傳遞一些數據到我template.php- > bind_global()中的Kohana 3.3

這裏是我的控制器:

class Controller_User extends Controller_Template { 

    public $template = 'template'; 

    public function action_index() { 

     $user = "Alice"; 

     $view = View::factory('user/user') 
      ->bind('user', $user); 

     $this->template->content = $view; 
    } 
} 

這樣做就意味着我可以在user/user.php訪問$user,和任何標記我有user/user.php$content可用。

不過,我想訪問$usertemplate.php。如果我改變bind()方法bind_global('user', $user)然後我可以在template.php確實訪問$user

但問題是,如果我這樣做,似乎什麼也沒有$content。我哪裏錯了?

回答

2

$view(或$content模板變量)結束,當你使用一個很好的理由bind_global()方法是空的 - 它是不返回任何靜態方法,並且因爲它是所謂的$view定義的最後一個方法變量最終變爲NULL

這是一個有點可惜(如果你問我)PHP允許使用對象上下文的靜態方法,而在同一時間,它不允許與性能。正是這種不一致(在其他許多方面)導致你的問題在這裏。

通過靜態調用bind_global()方法,可以實現全局綁定$user變量。完整的工作示例:

class Controller_User extends Controller_Template { 

    public $template = 'template'; 

    public function action_index() 
    { 
     $user = "Alice"; 
     View::bind_global('user', $user); 

     $view = View::factory('user/user'); 
     $this->template->content = $view; 
    } 
} 

而這應該適合你,就像一個魅力。

+0

偉大的答案。謝謝! –