drsh30452 2013-11-01 17:29
浏览 32
已采纳

查看Zend Framework 2中的模型

I was wondering if it is possible or how to be able to define a ViewModel in the Application module and pass it to display in the layout.phtml in Zend Framework 2. Here is the code for the Application Controller:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $container = new Container('session');

        return new ViewModel(array('username' => $container->username,
                                   'password' => $container->password));
    }
}

 This is the layout.phtml page I am trying to get username to display

 <ul class="nav navbar-nav navbar-right">
   <li><p class="navbar-text" style="font-family: Papyrus, fantasy; font-size: 20px;">       
     <?php echo $username; ?></p></li> 
  </ul> 

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongtu9823 2013-11-01 23:20
    关注

    If you want to display anything in layout ViewModel which is called root ViewModel you should use your controller`s layout() plugin:

    class IndexController extends AbstractActionController
    {
        public function indexAction()
        {
            $container = new Container('session');
            $mainLayout = $this->layout();
            $mainLayout->setVariable('foo', 'bar'); //it accepts array too 
            return new ViewModel(array('username' => $container->username,
                                   'password' => $container->password));
        }
    }
    

    In layout.phtml

    <?php echo $this->foo ;?> // or just $foo
    

    As a side note use plugins and view helpers for displaying user name or other user related stuff especial if your user is logged in. Check Zend\Authentication and plugin identity() its in Zend\Mvc\Controller\Plugin\Identity.php and check out its factory in Zend\Mvc\Controller\Plugin\Service\IdentityFactory.php

    You can always make your own identity plugin and use your custom factory to customize it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?