【问题标题】:Symfony3 Hook Up Annotation RoutesSymfony3 连接注释路由
【发布时间】:2016-04-15 12:06:31
【问题描述】:

我正在编写自己的基于 Symfony 组件构建的 PHP 框架作为学习练习。我按照http://symfony.com/doc/current/create_framework/index.html 上的教程创建了我的框架。

我现在想使用注释将我的路由与我的控制器连接起来。我目前有以下代码来设置路由:

// Create the route collection
$routes = new RouteCollection();

$routes->add('home', new Route('/{slug}', [
    'slug' => '',
    '_controller' => 'Controllers\HomeController::index',
]));

// Create a context using the current request
$context = new RequestContext();
$context->fromRequest($request);

// Create the url matcher
$matcher = new UrlMatcher($routes, $context);

// Try to get a matching route for the request
$request->attributes->add($matcher->match($request->getPathInfo()));

我遇到了以下类来加载注释,但我不知道如何使用它:

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Routing/Loader/AnnotationDirectoryLoader.php

如果有人可以提供帮助,我将不胜感激。

谢谢

【问题讨论】:

    标签: php annotations doctrine symfony


    【解决方案1】:

    我终于设法让它工作了。首先,我将包含 autoload.php 文件的位置更改为以下内容:

    use Doctrine\Common\Annotations\AnnotationRegistry;
    
    $loader = require __DIR__ . '/../vendor/autoload.php';
    
    AnnotationRegistry::registerLoader([$loader, 'loadClass']);
    

    然后我将路由收集位(在问题中)更改为:

    $reader = new AnnotationReader();
    
    $locator = new FileLocator();
    $annotationLoader = new AnnotatedRouteControllerLoader($reader);
    
    $loader = new AnnotationDirectoryLoader($locator, $annotationLoader);
    $routes = $loader->load(__DIR__ . '/../Controllers'); // Path to the app's controllers
    

    这里是 AnnotatedRouteControllerLoader 的代码:

    class AnnotatedRouteControllerLoader extends AnnotationClassLoader {
        protected function configureRoute(Route $route, ReflectionClass $class, ReflectionMethod $method, $annot) {
            $route->setDefault('_controller', $class->getName() . '::' . $method->getName());
        }
    }
    

    这取自https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/Routing/AnnotatedRouteControllerLoader.php。您可能希望对其进行修改以支持其他注释。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2014-11-01
      相关资源
      最近更新 更多