根据我的研究,公共方法getMatchedRouteName()的RouteResult实例中有这样的信息。问题是如何从视图中访问此实例。
我们知道我们可以从中间件的 __invoke() 方法中的 Request 对象中获取 RouteResult。
public function __invoke($request, $response, $next){
# instance of RouteResult
$routeResult = $request->getAttribute('Zend\Expressive\Router\RouteResult');
$routeName = $routeResult->getMatchedRouteName();
// ...
}
正如@timdev 建议的那样,我们将在现有的帮助程序 UrlHelper中找到灵感,并在自定义 View Helper 中进行几乎相同的实现。
简而言之,我们将创建 2 个类。
- CurrentUrlHelper与方法setRouteResult()和
- CurrentUrlMiddleware与__invoke($req, $res, $next)
我们将在 CurrentUrlMiddleware 中注入 CurrentUrlHelper,并在 __invoke() 方法中使用适当的 RouteResult 实例调用CurrentUrlHelper::setRouteResult() 。稍后我们可以在其中使用带有 RouteResult 实例的 CurrentUrlHelper。这两个类也应该有一个工厂。
class CurrentUrlMiddlewareFactory {
public function __invoke(ContainerInterface $container) {
return new CurrentUrlMiddleware(
$container->get(CurrentUrlHelper::class)
);
}
}
class CurrentUrlMiddleware {
private $currentUrlHelper;
public function __construct(CurrentUrlHelper $currentUrlHelper) {
$this->currentUrlHelper = $currentUrlHelper;
}
public function __invoke($request, $response, $next = null) {
$result = $request->getAttribute('Zend\Expressive\Router\RouteResult');
$this->currentUrlHelper->setRouteResult($result);
return $next($request, $response); # continue with execution
}
}
还有我们的新助手:
class CurrentUrlHelper {
private $routeResult;
public function __invoke($name) {
return $this->routeResult->getMatchedRouteName() === $name;
}
public function setRouteResult(RouteResult $result) {
$this->routeResult = $result;
}
}
class CurrentUrlHelperFactory{
public function __invoke(ContainerInterface $container){
# pull out CurrentUrlHelper from container!
return $container->get(CurrentUrlHelper::class);
}
}
现在我们只需要在配置中注册我们新的 View Helper 和 Middleware:
依赖项.global.php
'dependencies' => [
'invokables' => [
# dont have any constructor!
CurrentUrlHelper::class => CurrentUrlHelper::class,
],
]
中间件-pipeline.global.php
'factories' => [
CurrentUrlMiddleware::class => CurrentUrlMiddlewareFactory::class,
],
'middleware' => [
Zend\Expressive\Container\ApplicationFactory::ROUTING_MIDDLEWARE,
Zend\Expressive\Helper\UrlHelperMiddleware::class,
CurrentUrlMiddleware::class, # Our new Middleware
Zend\Expressive\Container\ApplicationFactory::DISPATCH_MIDDLEWARE,
],
最后我们可以在templates.global.php中注册我们的 View Helper
'view_helpers' => [
'factories' => [
# use factory to grab an instance of CurrentUrlHelper
'currentRoute' => CurrentUrlHelperFactory::class
]
],
现在您可以在任何模板文件中使用 helper :)
<?php // in layout.phtml file
$index_css = $this->currentRoute('home-page') ? 'active' : 'none';
$about_css = $this->currentRoute('about') ? 'active' : 'none';
$contact_css = $this->currentRoute('contact') ? 'active' : 'none';
?>