2016-04-15 40 views
4

我正在編寫自己的構建在Symfony組件之上的PHP框架作爲學習練習。我遵循在http://symfony.com/doc/current/create_framework/index.html找到的教程來創建我的框架。Symfony3搭建註釋路線

我現在想使用註釋將我的路線與我的控制器連接起來。目前,我有以下代碼設置路由:

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

我如果有人能幫忙,我會很感激。

謝謝

回答

4

我終於設法得到這個工作。首先,我改變了,我包括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。您可能希望修改它以支持其他註釋。

我希望這會有所幫助。