ZF2 - 将控制器名称放入布局/视图中 [英] ZF2 - Get controller name into layout/views

查看:13
本文介绍了ZF2 - 将控制器名称放入布局/视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用 ZF1,您将使用自定义视图助手检索模块/控制器名称,该助手将获取单例 frontController 对象并在那里获取名称.

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.

使用 ZF2,因为它们消除了框架的很多单例性质并引入了 DI,我在其中为该模块中的所有控制器指定了别名......我可以想象我会通过访问 DI 或也许将当前名称注入到布局中.

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.

谢谢,多姆

推荐答案

ZF2 出来了,骨架也出来了.这是在骨架顶部添加的,所以它应该是你最好的例子:

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

内部模块.php

public function onBootstrap($e)
{
    $e->getApplication()->getServiceManager()->get('translator');
    $e->getApplication()->getServiceManager()->get('viewhelpermanager')->setFactory('controllerName', function($sm) use ($e) {
        $viewHelper = new ViewHelperControllerName($e->getRouteMatch());
        return $viewHelper;
    });

    $eventManager        = $e->getApplication()->getEventManager();
    $moduleRouteListener = new ModuleRouteListener();
    $moduleRouteListener->attach($eventManager);
}

实际的 ViewHelper:

The actual ViewHelper:

// Application/View/Helper/ControllerName.php

namespace ApplicationViewHelper;

use ZendViewHelperAbstractHelper;

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

这篇关于ZF2 - 将控制器名称放入布局/视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆