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 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题