doudou2121 2012-01-12 22:12 采纳率: 50%
浏览 38
已采纳

ZF2 - 将控制器名称放入布局/视图中

I know with ZF1 you would retrieve the module/controller name using custom View Helpers that would get the singleton frontController object and get the name there.

Using ZF2 as they've abolished alot of the singleton nature of the framework and introduced DI where I've specified aliases for all of my controllers within this module... I can imagine I would get it through accessing the DI or perhaps injecting the current name into the layout.

Anyone got any idea how you would do it. I guess there a hundred different ways but after sniffing about the code for a few hours I can't really figure out how its meant to be done now.

The reason I wanted the controller name is to add it to the body as a class for specific controller styling.

Thanks, Dom

  • 写回答

8条回答 默认 最新

  • dqh19413 2012-10-25 19:38
    关注

    ZF2 is out and so is the skeleton. This is adding on top of the skeleton so it should be your best example:

    Inside Module.php

    public function onBootstrap($e)
    {
        $e->getApplication()->getServiceManager()->get('translator');
        $e->getApplication()->getServiceManager()->get('viewhelpermanager')->setFactory('controllerName', function($sm) use ($e) {
            $viewHelper = new View\Helper\ControllerName($e->getRouteMatch());
            return $viewHelper;
        });
    
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }
    

    The actual ViewHelper:

    // Application/View/Helper/ControllerName.php
    
    namespace Application\View\Helper;
    
    use Zend\View\Helper\AbstractHelper;
    
    class ControllerName extends AbstractHelper
    {
    
    protected $routeMatch;
    
        public function __construct($routeMatch)
        {
            $this->routeMatch = $routeMatch;
        }
    
        public function __invoke()
        {
            if ($this->routeMatch) {
                $controller = $this->routeMatch->getParam('controller', 'index');
                return $controller;
            }
        }
    }
    

    Inside any of your views/layouts

    echo $this->controllerName()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了