symfony/routing
Symfony Routing maps HTTP requests to routes and parameters, and generates URLs from route definitions. Define Route and RouteCollection, then use UrlMatcher to match paths and UrlGenerator to build links based on a RequestContext.
To leverage symfony/routing in Laravel, start by installing the package:
composer require symfony/routing
Laravel already abstracts routing, but you can use Symfony's routing directly for custom logic:
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\RequestContext;
// Define routes
$routes = new RouteCollection();
$routes->add('blog_show', new Route('/blog/{slug}', [
'_controller' => 'App\Http\Controllers\BlogController@show',
]));
// Match a request
$context = new RequestContext();
$matcher = new UrlMatcher($routes, $context);
$params = $matcher->match('/blog/hello-world');
// Generate a URL
$generator = new UrlGenerator($routes, $context);
$url = $generator->generate('blog_show', ['slug' => 'hello-world']);
Illuminate\Routing\Router for Laravel-specific routing, but Symfony's routing is useful for:
Define routes programmatically or via YAML/JSON (Symfony's format, but adaptable to Laravel):
// Programmatic route definition
$route = new Route('/user/{id}', [
'_controller' => 'App\Http\Controllers\UserController@show',
'methods' => ['GET', 'HEAD'],
'requirements' => ['id' => '\d+'],
]);
$routes->add('user_show', $route);
Use RequestContext to manage global routing parameters (e.g., base URL, scheme):
$context = new RequestContext();
$context->setBaseUrl('https://example.com');
$context->setScheme('https');
Generate URLs with query strings dynamically:
$url = $generator->generate('blog_show', [
'slug' => 'post-1',
], UrlGenerator::ABSOLUTE_URL, [
'page' => 2,
'sort' => 'desc',
]);
// Output: /blog/post-1?page=2&sort=desc
Match routes while respecting HTTP methods:
$matcher = new UrlMatcher($routes, $context);
$params = $matcher->matchRequest($request); // Uses $request->getMethod()
Use Symfony's routing to generate URLs in controllers:
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class BlogController extends Controller
{
public function show(UrlGeneratorInterface $urlGenerator)
{
$url = $urlGenerator->generate('blog_show', ['slug' => 'test']);
return view('blog.show')->with('url', $url);
}
}
Load routes from external sources (e.g., API responses, database):
$routes = new RouteCollection();
foreach ($apiRoutes as $name => $routeData) {
$routes->add($name, new Route($routeData['path'], $routeData['defaults']));
}
Define constraints for route parameters:
$route = new Route('/post/{year}/{month}/{day}', [], [
'year' => '\d{4}',
'month' => '(0[1-9]|1[0-2])',
'day' => '(0[1-9]|[12][0-9]|3[01])',
]);
Case Sensitivity in Host Matching
RequestContext::setHost() carefully.strtolower()) if case-insensitive matching is needed.Query Parameter Handling
?0=value) may be renumbered. Use associative arrays for stability:
$url = $generator->generate('route_name', [], UrlGenerator::ABSOLUTE_URL, ['page' => 1]);
Circular References in Route Collections
RouteCollection::addCollection() for nested routes.URL Generation with Absolute Paths
UrlGenerator::ABSOLUTE_URL generates full URLs, but ensure RequestContext is properly configured with baseUrl and scheme.Route Overrides
RouteCollection::get() to check for conflicts.Dump Route Parameters
Use var_dump($matcher->match('/path')) to inspect matched parameters and debug issues.
Check Route Requirements
If a route isn't matching, verify requirements (e.g., regex constraints) and defaults.
Enable Route Debugging in Laravel Use Laravel's built-in route listing:
php artisan route:list
Or dump Symfony's route collection:
dd($routes->getIterator());
Request Context Persistence
RequestContext is stateless. Recreate it for each request or persist it (e.g., in middleware).
Host and Scheme Defaults
If RequestContext isn't configured, generated URLs may omit the scheme or host. Set defaults:
$context->setScheme('https');
$context->setHost('example.com');
Route Name Conflicts Laravel and Symfony may handle route names differently. Prefix Symfony routes:
$routes->add('symfony_blog_show', $route);
Custom Route Loaders
Extend RouteLoaderInterface to load routes from custom sources (e.g., database, API).
Route Compilation
Use RouteCompiler to pre-compile routes for performance-critical applications.
Middleware Integration
Integrate Symfony's routing with Laravel middleware by wrapping UrlMatcher or UrlGenerator in a service provider:
$this->app->singleton(UrlGeneratorInterface::class, function ($app) {
return new UrlGenerator($app['routes'], $app['request_context']);
});
Attribute-Based Routing Leverage Symfony's attribute-based routing (v8+) in Laravel by creating a custom loader:
use Symfony\Component\Routing\Loader\AttributeLoader;
$loader = new AttributeLoader($controllerClass);
$routes = $loader->load(__DIR__.'/../src/Http/Controllers');
Route Caching Cache compiled routes for better performance:
$compiler = new RouteCompiler();
$compiledRoutes = $compiler->compile($routes);
How can I help you explore Laravel packages today?