The Routing Component
The Routing component maps an HTTP request to a set of configurationvariables. It's used to build routing systems for web applications whereeach URL is associated with some code to execute.
Installation
- $ composer require symfony/routing
Note
If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php
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.
Routing System Setup
A routing system has three parts:
- A
RouteCollection
, which contains theroute definitions (instances of the classRoute
); - A
RequestContext
, 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 RouteCollection::add()
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 UrlMatcher::match()
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
- 'context.getHost() matches "/(secure|admin).example.com/"' // condition
- );
- // ...
- $parameters = $matcher->match('/archive/2012-01');
- // [
- // '_controller' => 'showArchive',
- // 'month' => '2012-01',
- // 'subdomain' => 'www',
- // '_route' => ...
- // ]
- $parameters = $matcher->match('/archive/foo');
- // throws ResourceNotFoundException
Route Collections
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
The RequestContext
provides informationabout the current request. You can define all parameters of an HTTP requestwith this class via its constructor:
- public function __construct(
- $baseUrl = '',
- $method = 'GET',
- $host = 'localhost',
- $scheme = 'http',
- $httpPort = 80,
- $httpsPort = 443,
- $path = '/',
- $queryString = ''
- )
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 itsRequest
class to feed theRequestContext
in a shortcut:
- use Symfony\Component\HttpFoundation\Request;
- $context = new RequestContext();
- $context->fromRequest(Request::createFromGlobals());
Loading Routes
The Routing component comes with a number of loader classes, each giving you theability to load a collection of route definitions from external resources.
File Routing Loaders
Each loader expects a FileLocator
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 RouteCollection
.
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:
XmlFileLoader
PhpFileLoader
If you use thePhpFileLoader
youhave to provide the name of a PHP file which returns a callable handling aRoutingConfigurator
.This class allows to chain imports, collections or simple route definition calls:
- // RouteProvider.php
- use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
- return function (RoutingConfigurator $routes) {
- $routes->add('route_name', '/foo')
- ->controller('ExampleController')
- // ...
- ;
- };
Closure Routing Loaders
There is also the ClosureLoader
, whichcalls a closure and uses the result as a RouteCollection
:
- use Symfony\Component\Routing\Loader\ClosureLoader;
- $closure = function () {
- return new RouteCollection();
- };
- $loader = new ClosureLoader();
- $routes = $loader->load($closure);
Annotation Routing Loaders
Last but not least there areAnnotationDirectoryLoader
andAnnotationFileLoader
to loadroute definitions from class annotations:
- 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 all-in-one Router
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:
- public function __construct(
- LoaderInterface $loader,
- $resource,
- array $options = [],
- RequestContext $context = null,
- LoggerInterface $logger = null
- );
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 theRouter
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.
Learn more
- Routing
- How to Create a custom Route Loader
- Looking up Routes from a Database: Symfony CMF DynamicRouter
- Controller
- Extending Action Argument Resolving
- How to Customize Error Pages
- How to Forward Requests to another Controller
- How to Define Controllers as Services
- How to Create a SOAP Web Service in a Symfony Controller
- How to Upload Files