ZF2-コントローラー名をレイアウト/ビューに入れます
-
27-10-2019 - |
質問
ZF1では、Singleton FrontControllerオブジェクトを取得してそこに名前を取得するカスタムビューヘルパーを使用して、モジュール/コントローラー名を取得することを知っています。
ZF2を使用して、彼らがフレームワークのシングルトンの性質の多くを廃止し、このモジュール内のすべてのコントローラーにエイリアスを指定したDIを導入しました... DIにアクセスするか、おそらく注射することでそれを取得すると想像できます。レイアウトへの現在の名前。
誰もがあなたがそれをどのように行うかについての考えを得ました。私は100の異なる方法があると思いますが、数時間コードについて嗅いだ後、私はそれが今どのように行われるべきかを本当に理解することができません。
コントローラー名を望んでいた理由は、特定のコントローラースタイリングのクラスとしてボディに追加することです。
ありがとう、dom
解決
ZF2が外出しており、スケルトンも外出しています。これはスケルトンの上に追加されているので、それはあなたの最良の例です:
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);
}
実際のビューヘルパー:
// 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;
}
}
}
ビュー/レイアウトのいずれか内
echo $this->controllerName()
他のヒント
これは私がzf2 beta5で作業するようになった解決策です
モジュール/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());
});
}
...
}
モジュール/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;
}
}
任意のViewFileで
$this->myviewalias()->echoController();
拡張する代わりに onBootStrap()
の Module.php
, 、使用できます getViewHelperConfig()
(inも 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;
},
),
);
}
ここの短いコード:
$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));
ナビゲーションメニューの部分的な現在のモジュール/コントローラー/ルート名にアクセスしたかったのですが、カスタムビューヘルパーを実装してアクセスするしかありませんでした。以下を思いつきました。ここに投稿しています。
<?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;
}
}
レイアウト/表示の値にアクセスするために、ここに私がそれを行う方法があります。
1. $this->currentRequest()->get('module');
2. $this->currentRequest()->get('controller');
3. $this->currentRequest()->get('action');
4. $this->currentRequest()->get('route');
これが誰かを助けることを願っています。
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();
}
私が作成しました currentroute この目的のためにヘルパーを表示します。
インストール:
composer require tasmaniski/zf2-current-route
モジュールを登録します config/application.config.php:
'modules' => array(
'...',
'CurrentRoute'
),
任意のビュー/レイアウトファイルで使用します。
$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
完全なドキュメントとコードを見ることができます https://github.com/tasmaniski/zf2-current-route
$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));