ZF2 - Get controller name into layout/views

前端 未结 9 1595
逝去的感伤
逝去的感伤 2020-11-30 07:03

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.

U

9条回答
  •  一个人的身影
    2020-11-30 07:16

    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()
    

提交回复
热议问题