php ZF2 - 将控制器名称获取到布局/视图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8843092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ZF2 - Get controller name into layout/views
提问by Intellix
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.
我知道使用 ZF1,您将使用自定义视图助手检索模块/控制器名称,该助手将获取单例 frontController 对象并在那里获取名称。
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.
使用 ZF2,因为他们已经废除了框架的很多单例性质并引入了 DI,我在这个模块中为我的所有控制器指定了别名......我可以想象我会通过访问 DI 或注入当前名称进入布局。
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
谢谢,多姆
采纳答案by Intellix
ZF2 is out and so is the skeleton. This is adding on top of the skeleton so it should be your best example:
ZF2 出局了,骨架也出局了。这是在骨架顶部添加的,所以它应该是你最好的例子:
Inside Module.php
内部模块.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:
实际的 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()
回答by Borje
This would be a solution I got to work with zf2 beta5
这将是我使用 zf2 beta5 的解决方案
module/MyModule/Module.php
模块/MyModule/Module.php
namespace MyModule;
use Zend\Mvc\ModuleRouteListener;
use MyModule\View\Helper as MyViewHelper;
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$serviceManager = $app->getServiceManager();
$serviceManager->get('viewhelpermanager')->setFactory('myviewalias', function($sm) use ($e) {
return new MyViewHelper($e->getRouteMatch());
});
}
...
}
module/MyModule/src/MyModule/View/Helper.php
模块/MyModule/src/MyModule/View/Helper.php
namespace MyModule\View;
use Zend\View\Helper\AbstractHelper;
class Helper extends AbstractHelper
{
protected $route;
public function __construct($route)
{
$this->route = $route;
}
public function echoController()
{
$controller = $this->route->getParam('controller', 'index');
echo $controller;
}
}
In any viewfile
在任何视图文件中
$this->myviewalias()->echoController();
回答by dstj
instead of extending onBootStrap()
in Module.php
, you can use getViewHelperConfig()
(also in Module.php
). The actual helper is unchanged, but you get the following code to create it:
而不是扩展onBootStrap()
in Module.php
,您可以使用getViewHelperConfig()
(也在Module.php
)。实际的帮助程序没有改变,但您可以使用以下代码来创建它:
public function getViewHelperConfig()
{
return array(
'factories' => array(
'ControllerName' => function ($sm) {
$match = $sm->getServiceLocator()->get('application')->getMvcEvent()->getRouteMatch();
$viewHelper = new \Application\View\Helper\ControllerName($match);
return $viewHelper;
},
),
);
}
回答by James Labs
Short Code here :
短代码在这里:
$this->getHelperPluginManager()->getServiceLocator()->get('application')->getMvcEvent()->getRouteMatch()->getParam('action', 'index');
$controller = $this->getHelperPluginManager()->getServiceLocator()->get('application')->getMvcEvent()->getRouteMatch()->getParam('controller', 'index');
$controller = array_pop(explode('\', $controller));
回答by Ibrahim Azhar Armar
I wanted to access current module/controller/route name in navigation menu partial and there was no way but to implement custom view helper and access it, i came up with the following, i am posting it here.
我想在导航菜单部分访问当前模块/控制器/路由名称,但别无他法,只能实现自定义视图助手并访问它,我想出了以下内容,我将其发布在这里。
<?php
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
/**
* View Helper to return current module, controller & action name.
*/
class CurrentRequest extends AbstractHelper
{
/**
* Current Request parameters
*
* @access protected
* @var array
*/
protected $params;
/**
* Current module name.
*
* @access protected
* @var string
*/
protected $moduleName;
/**
* Current controller name.
*
* @access protected
* @var string
*/
protected $controllerName;
/**
* Current action name.
*
* @access protected
* @var string
*/
protected $actionName;
/**
* Current route name.
*
* @access protected
* @var string
*/
protected $routeName;
/**
* Parse request and substitute values in corresponding properties.
*/
public function __invoke()
{
$this->params = $this->initialize();
return $this;
}
/**
* Initialize and extract parameters from current request.
*
* @access protected
* @return $params array
*/
protected function initialize()
{
$sm = $this->getView()->getHelperPluginManager()->getServiceLocator();
$router = $sm->get('router');
$request = $sm->get('request');
$matchedRoute = $router->match($request);
$params = $matchedRoute->getParams();
/**
* Controller are defined in two patterns.
* 1. With Namespace
* 2. Without Namespace.
* Concatenate Namespace for controller without it.
*/
$this->controllerName = !strpos($params['controller'], '\') ?
$params['__NAMESPACE__'].'\'.$params['controller'] :
$params['controller'];
$this->actionName = $params['action'];
/**
* Extract Module name from current controller name.
* First camel cased character are assumed to be module name.
*/
$this->moduleName = substr($this->controllerName, 0, strpos($this->controllerName, '\'));
$this->routeName = $matchedRoute->getMatchedRouteName();
return $params;
}
/**
* Return module, controller, action or route name.
*
* @access public
* @return $result string.
*/
public function get($type)
{
$type = strtolower($type);
$result = false;
switch ($type) {
case 'module':
$result = $this->moduleName;
break;
case 'controller':
$result = $this->controllerName;
break;
case 'action':
$result = $this->actionName;
break;
case 'route':
$result = $this->routeName;
break;
}
return $result;
}
}
In order to access the values in layout/view here is how i do it.
为了访问布局/视图中的值,我是这样做的。
1. $this->currentRequest()->get('module');
2. $this->currentRequest()->get('controller');
3. $this->currentRequest()->get('action');
4. $this->currentRequest()->get('route');
Hope this helps someone.
希望这可以帮助某人。
回答by tasmaniski
I created CurrentRouteView Helper for this purpose.
为此,我创建了CurrentRouteView Helper。
Install it:
安装它:
composer require tasmaniski/zf2-current-route
Register module in config/application.config.php:
在config/application.config.php 中注册模块:
'modules' => array(
'...',
'CurrentRoute'
),
Use it in any view/layout file:
在任何视图/布局文件中使用它:
$this->currentRoute()->getController(); // return current controller name
$this->currentRoute()->getAction(); // return current action name
$this->currentRoute()->getModule(); // return current module name
$this->currentRoute()->getRoute(); // return current route name
You can see full documentation and code https://github.com/tasmaniski/zf2-current-route
你可以看到完整的文档和代码https://github.com/tasmaniski/zf2-current-route
回答by rdo
In zf2 beta4 it made in this manner:
在 zf2 beta4 中,它以这种方式制作:
public function init(ModuleManager $moduleManager)
{
$sharedEvents = $moduleManager->events()->getSharedManager();
$sharedEvents->attach('bootstrap', 'bootstrap', array($this, 'onBootstrap'));
}
public function onBootstrap($e)
{
$app = $e->getParam('application');
// some your code here
$app->events()->attach('route', array($this, 'onRouteFinish'), -100);
}
public function onRouteFinish($e)
{
$matches = $e->getRouteMatch();
$controller = $matches->getParam('controller');
var_dump($controller);die();
}
回答by Maneesh Mehta
$this->getHelperPluginManager()->getServiceLocator()->get('application')
->getMvcEvent()->getRouteMatch()->getParam('action', 'index');
$controller = $this->getHelperPluginManager()->getServiceLocator()
->get('application')->getMvcEvent()->getRouteMatch()
->getParam('controller', 'index');
$controller = explode('\', $controller);
print_r(array_pop($controller));
回答by Kamlesh
Get controller / action name in controller in Zend-3 framework
在 Zend-3 框架中的控制器中获取控制器/动作名称
private function getControllerActionName()
{
$currentController = $this->getEvent()->getRouteMatch()->getParam('controller', 'index');
$explode_controller = explode('\', $currentController);
$currentController = strtolower(array_pop($explode_controller));
$currentController = str_replace('controller', '', $currentController);
$currentAction = strtolower($this->getEvent()->getRouteMatch()->getParam('action', 'index'));
return array(
'controller' => $currentController,
'action' => $currentAction,
);
}
It works for me. I hope, this will also help you. Thanks for asking this question.
这个对我有用。我希望,这也能帮助你。感谢您提出这个问题。