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

现在,我想使用注释将路线与 Controller 连接起来。我目前有以下代码来设置路由:

// 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

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

谢谢

最佳答案

我终于设法解决了这个问题。首先,我将包含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。您可能希望对其进行修改以支持其他注释。

我希望这有帮助。

10-05 20:28
查看更多