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.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line