2014-02-27 112 views
1

如何在視圖內呈現控制器的結果...?從視圖調用控制器 - Zend Framework

這是我目前正在做的,但作爲視圖直接調用...它不會從我的控制器中獲取模型。這是愚蠢的。

public function ListAction() 
{ 
    $sm = $this->getServiceLocator(); 
    $this->userRepository = $sm->get('Application\Model\Concrete\TGUserRepository'); 

    $users = $this->userRepository->Users(); 

    $view = new ViewModel(array("Users" => $users)); 

     $secondarySidebarView = new ViewModel(); // I don't really wanna do this, because I've already got an awesome controller set up for this which may as well be used to generate the model :S ? 
     $secondarySidebarView->setTemplate('something/poo'); // This only gets the view and doesn't call the controller first :S 

    $view->addChild($secondarySidebarView, 'something'); 
    return $view; 
} 

觀點:

<?php  
    foreach($this->Users as $user) 
    { 
     echo $user->Email; 
    } 

    echo $this->something; // Works fine 
    print_r($this->something->Poos); // Crashes because the controller hasn't been called to generate the Poos :(

我想我的觀點裏做的是這樣的:

echo RenderFromController("action", "controllername"); 
+0

不確定你想要在這裏做什麼。爲什麼視圖需要訪問模型?所有數據都應該建模並傳遞給視圖。你是否遵循MVC模式? – Gavin

+1

它不適用於視圖,但可以使用[forward controller plugin](http://framework.zend.com/manual/2.1/en/modules/zend.mvc.plugins.html#zend-mvc-控制器 - 插件 - 轉發)使用你的真棒動作;) – jmleroux

+0

@gavin - 視圖不需要訪問模型...控制器可以訪問模型,視圖調用控制器,然後獲取需要的內容 – Jimmyt1988

回答

0

這裏有一個方法來做到這一點:

public function listAction() 
{ 

    $view = new ViewModel(); 
    $view->setTemplate('users.phtml'); 
    $poos = $this->forward() 
        ->dispatch('Foo\Controller', array('action' => 'action-name')); 
    $view->addChild($poos, 'Poos'); 

    /* Add more variables to $view as needed */ 

    return $view; 
} 

in users.phtml

<?php 

    echo $this->poos; //Will output the result of Foo\Controller::action-name 
相關問題