The Routing Component
Note
If you install this component outside of a Symfony application, you mustrequire the file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.
Usage
The main Symfony routing article explains all the features ofthis component when used inside a Symfony application. This article onlyexplains the things you need to do to use it in a non-Symfony PHP application.
A routing system has three parts:
- A
, which contains theroute definitions (instances of the class
Route
); - A
, which has informationabout the request;
- A
UrlMatcher
, which performsthe mapping of the path to a single route.Here is a quick example:
- use App\Controller\BlogController;
- use Symfony\Component\Routing\Generator\UrlGenerator;
- use Symfony\Component\Routing\Matcher\UrlMatcher;
- use Symfony\Component\Routing\RequestContext;
- use Symfony\Component\Routing\Route;
- use Symfony\Component\Routing\RouteCollection;
- $route = new Route('/blog/{slug}', ['_controller' => BlogController::class]);
- $routes = new RouteCollection();
- $routes->add('blog_show', $route);
- $context = new RequestContext('/');
- // Routing can match routes with incoming requests
- $matcher = new UrlMatcher($routes, $context);
- $parameters = $matcher->match('/blog/lorem-ipsum');
- // $parameters = [
- // '_controller' => 'App\Controller\BlogController',
- // 'slug' => 'lorem-ipsum',
- // '_route' => 'blog_show'
- // ]
- // Routing can also generate URLs for a given route
- $generator = new UrlGenerator($routes, $context);
- $url = $generator->generate('blog_show', [
- 'slug' => 'my-blog-post',
- ]);
- // $url = '/blog/my-blog-post'
The method takes two arguments. The first is the name of the route. The secondis a
Route
object, which expects aURL path and some array of custom variables in its constructor. This arrayof custom variables can be anything that's significant to your application,and is returned when that route is matched.
The returns the variables you set on the route as well as the route parameters.Your application can now use this information to continue processing the request.In addition to the configured variables, a
_route
key is added, which holdsthe name of the matched route.
If no matching route can be found, aResourceNotFoundException
willbe thrown.
Defining Routes
A full route definition can contain up to eight parts:
- $route = new Route(
- '/archive/{month}', // path
- ['_controller' => 'showArchive'], // default values
- ['month' => '[0-9]{4}-[0-9]{2}', 'subdomain' => 'www|m'], // requirements
- [], // options
- '{subdomain}.example.com', // host
- [], // schemes
- [], // methods
- );
- // ...
- $parameters = $matcher->match('/archive/2012-01');
- // [
- // '_controller' => 'showArchive',
- // 'month' => '2012-01',
- // 'subdomain' => 'www',
- // '_route' => ...
- // ]
- $parameters = $matcher->match('/archive/foo');
- // throws ResourceNotFoundException
You can add routes or other instances ofRouteCollection
to another collection.This way you can build a tree of routes. Additionally you can define commonoptions for all routes of a subtree using methods provided by theRouteCollection
class:
- $rootCollection = new RouteCollection();
- $subCollection = new RouteCollection();
- $subCollection->add(...);
- $subCollection->add(...);
- $subCollection->addPrefix('/prefix');
- $subCollection->addDefaults([...]);
- $subCollection->addRequirements([...]);
- $subCollection->addOptions([...]);
- $subCollection->setHost('{subdomain}.example.com');
- $subCollection->setMethods(['POST']);
- $subCollection->setSchemes(['https']);
- $subCollection->setCondition('context.getHost() matches "/(secure|admin).example.com/"');
- $rootCollection->addCollection($subCollection);
Setting the Request Parameters
Normally you can pass the values from the $SERVER
variable to populate theRequestContext
. But if you use the[_HttpFoundation]($e202783772dc89dd.md) component, you can use its class to feed the
RequestContext
in a shortcut:
- use Symfony\Component\HttpFoundation\Request;
- $context = new RequestContext();
- $context->fromRequest(Request::createFromGlobals());
The Routing component comes with a number of loader classes, each giving you theability to load a collection of route definitions from external resources.
Each loader expects a instanceas the constructor argument. You can use the
FileLocator
to define an array of paths in which the loader will look for the requested files.If the file is found, the loader returns a .
If you're using the YamlFileLoader
, then route definitions look like this:
- # routes.yaml
- route1:
- path: /foo
- controller: MyController::fooAction
- methods: GET|HEAD
- route2:
- path: /foo/bar
- controller: FooBarInvokableController
- methods: PUT
To load this file, you can use the following code. This assumes that yourroutes.yaml
file is in the same directory as the below code:
- use Symfony\Component\Config\FileLocator;
- use Symfony\Component\Routing\Loader\YamlFileLoader;
- // looks inside *this* directory
- $fileLocator = new FileLocator([__DIR__]);
- $loader = new YamlFileLoader($fileLocator);
- $routes = $loader->load('routes.yaml');
Besides YamlFileLoader
there are twoother loaders that work the same way:
- If you use the
PhpFileLoader
youhave to provide the name of a PHP file which returns a callable handling a.This class allows to chain imports, collections or simple route definition calls:
There is also the ClosureLoader
, whichcalls a closure and uses the result as a :
- $closure = function () {
- return new RouteCollection();
- };
- $loader = new ClosureLoader();
- $routes = $loader->load($closure);
- use Doctrine\Common\Annotations\AnnotationReader;
- use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader;
- use Symfony\Component\Config\FileLocator;
- use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
- $loader = new AnnotationDirectoryLoader(
- new FileLocator(__DIR__.'/app/controllers/'),
- new AnnotatedRouteControllerLoader(
- new AnnotationReader()
- )
- );
- $routes = $loader->load(__DIR__.'/app/controllers/');
- // ...
Note
In order to use the annotation loader, you should have installed thedoctrine/annotations
and doctrine/cache
packages with Composer.
Tip
Annotation classes aren't loaded automatically, so you must load themusing a class loader like this:
- use Composer\Autoload\ClassLoader;
- use Doctrine\Common\Annotations\AnnotationRegistry;
- /** @var ClassLoader $loader */
- $loader = require __DIR__.'/../vendor/autoload.php';
- AnnotationRegistry::registerLoader([$loader, 'loadClass']);
- return $loader;
The Router
class is an all-in-one packageto use the Routing component. The constructor expects a loader instance,a path to the main route definition and some other settings:
With the cache_dir
option you can enable route caching (if you provide apath) or disable caching (if it's set to null
). The caching is doneautomatically in the background if you want to use it. A basic example of the class would look like:
- $fileLocator = new FileLocator([__DIR__]);
- $requestContext = new RequestContext('/');
- $router = new Router(
- new YamlFileLoader($fileLocator),
- 'routes.yaml',
- ['cache_dir' => __DIR__.'/cache'],
- $requestContext
- );
- $parameters = $router->match('/foo/bar');
- $url = $router->generate('some_route', ['parameter' => 'value']);
Note
If you use caching, the Routing component will compile new classes whichare saved in the cache_dir
. This means your script must have writepermissions for that location.