在我的 Symfony 3.2 应用程序中,我创建了一个自定义路由器,该路由器扩展自Symfony\Bundle\FrameworkBundle\Routing\Router
.
根据需要,它实现了getRouteCollection()
method:
public function getRouteCollection() {
$locator = new FileLocator(__DIR__ . '/../Controller');
$annotationReader = new Doctrine\Common\Annotations\AnnotationReader();
$classLoader = new AnnotationClassLoader($annotationReader);
$routeLoader = new Symfony\Component\Routing\Loader\AnnotationDirectoryLoader($locator, $classLoader);
$routes = $routeLoader->load('.\\', 'annotation');
return $routes;
}
The AnnotationClassLoader
这里使用的是我自己的,它扩展了摘要Symfony\Component\Routing\Loader\AnnotationClassLoader
班级。它只实现了一种方法:
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot) {
$route->setDefault('_controller', '???');
return $route;
}
我想用它来设置注释中找到的路由的默认控制器。这AnnotationReader
从源代码中读取所有路由都很好,但它根本没有设置它们的默认控制器,这就是我想要做的configureRoute
。该函数似乎在找到的每条路线上都会被调用。
现在的问题是找到合适的表达式来替换'???'
with.最后,我需要一个结果,例如'MyPluginBundle:ControllerName:actionName'
。这意味着我要么需要用我所拥有的信息(即函数的四个参数)构建该字符串,要么我采取了完全错误的方法,并且有一种更简单的方法可以做到这一点。
示例转储$route
:
如您所见,没有默认值_controller
yet.
object(Symfony\Component\Routing\Route)
private 'path' => string '/my/route' (length=9)
private 'host' => string '' (length=0)
private 'schemes' =>
array (size=0)
empty
private 'methods' =>
array (size=0)
empty
private 'defaults' =>
array (size=0)
empty
private 'requirements' =>
array (size=0)
empty
private 'options' =>
array (size=1)
'compiler_class' => string 'Symfony\Component\Routing\RouteCompiler' (length=39)
private 'compiled' => null
private 'condition' => string '' (length=0)
示例转储$class
:
object(ReflectionClass)
public 'name' => string 'MyPluginBundle\Controller\DefaultController' (length=43)
示例转储$method
:
object(ReflectionMethod)[174]
public 'name' => string 'indexAction' (length=11)
public 'class' => string 'MyPluginBundle\Controller\DefaultController' (length=43)
示例转储$annot
:
object(Sensio\Bundle\FrameworkExtraBundle\Configuration\Route)
protected 'service' => null
private 'path' (Symfony\Component\Routing\Annotation\Route) => string '/my/route' (length=9)
private 'name' (Symfony\Component\Routing\Annotation\Route) => string 'name_of_the_route' (length=17)
private 'requirements' (Symfony\Component\Routing\Annotation\Route) =>
array (size=0)
empty
private 'options' (Symfony\Component\Routing\Annotation\Route) =>
array (size=0)
empty
private 'defaults' (Symfony\Component\Routing\Annotation\Route) =>
array (size=0)
empty
private 'host' (Symfony\Component\Routing\Annotation\Route) => null
private 'methods' (Symfony\Component\Routing\Annotation\Route) =>
array (size=0)
empty
private 'schemes' (Symfony\Component\Routing\Annotation\Route) =>
array (size=0)
empty
private 'condition' (Symfony\Component\Routing\Annotation\Route) => null