gpt4 book ai didi

php - Symfony 3 连接注释路由

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:34:53 24 4
gpt4 key购买 nike

作为学习练习,我正在编写自己的基于 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 .您可能希望修改它以支持其他注释。

希望对您有所帮助。

关于php - Symfony 3 连接注释路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36646707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com