问题描述
我知道使用ZF1,您将使用自定义的View Helpers检索模块/控制器名称,该自定义View Helpers将获得单例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.
谢谢,Dom
推荐答案
ZF2失效了,骨架也失效了.这是最基本的内容,因此它应该是您最好的例子:
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
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);
}
实际的ViewHelper:
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()
这篇关于ZF2-将控制器名称添加到布局/视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!