Home >Backend Development >PHP Tutorial >Set up routing in PHP applications using Symfony routing component
The Symfony routing component is a very popular routing component that is adapted from several frameworks and provides a lot of flexibility if you want to set up routing in your PHP application.
If you have built a custom PHP application and are looking for a feature-rich routing library, then Symfony Routing Component is one of the best candidates. It also allows you to define your application's routes in YAML format.
Starting with installation and configuration, we will demonstrate the various options of this component for routing configuration through practical examples. In this article you will learn:
In this section, we will install the libraries required to set up routing in a PHP application. I assume you already have Composer installed on your system as we need it to install the necessary libraries available on Packagist.
After installing Composer, please continue using the following commands to install the core routing components.
$composer require symfony/routing
While the routing component itself is sufficient to provide comprehensive routing capabilities in your application, we will also go ahead and install a few additional components to make our lives easier and enrich the existing core routing functionality.
First, we will proceed to install the HttpFoundation component, which provides object-oriented wrappers for PHP global variables and response-related functions. It ensures that you don't need to directly access global variables like $_GET
, $_POST
, etc.
$composer require symfony/http-foundation
Next, if you want to define application routes in a YAML file instead of PHP code, the YAML component comes into play as it helps you convert YAML strings to PHP arrays and vice versa.
$composer require symfony/yaml
Finally, we will install the Config component, which provides several utility classes to initialize and process configuration values defined in different types of files (such as YAML, INI, XML, etc.). In our case we will use this to load routes from a YAML file.
$composer require symfony/config
That’s the installation part, but how are you supposed to use it? In fact, just include the autoload.php file created by Composer in your application, as shown in the following code snippet.
<?php require_once './vendor/autoload.php'; // application code ?>
In the previous section, we completed the installation of the necessary routing components. Now you can instantly set up routing in your PHP application.
Let's go ahead and create the basic_routes.php file with the following content.
<?php require_once './vendor/autoload.php'; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGenerator; use Symfony\Component\Routing\Exception\ResourceNotFoundException; try { // Init basic route $foo_route = new Route( '/foo', array('controller' => 'FooController') ); // Init route with dynamic placeholders $foo_placeholder_route = new Route( '/foo/{id}', array('controller' => 'FooController', 'method'=>'load'), array('id' => '[0-9]+') ); // Add Route object(s) to RouteCollection object $routes = new RouteCollection(); $routes->add('foo_route', $foo_route); $routes->add('foo_placeholder_route', $foo_placeholder_route); // Init RequestContext object $context = new RequestContext(); $context->fromRequest(Request::createFromGlobals()); // Init UrlMatcher object $matcher = new UrlMatcher($routes, $context); // Find the current route $parameters = $matcher->match($context->getPathInfo()); // How to generate a SEO URL $generator = new UrlGenerator($routes, $context); $url = $generator->generate('foo_placeholder_route', array( 'id' => 123, )); echo '<pre class="brush:php;toolbar:false">'; print_r($parameters); echo 'Generated URL: ' . $url; exit; } catch (ResourceNotFoundException $e) { echo $e->getMessage(); }
Setting up routing using the Symfony Routing component usually involves a series of steps listed below.
Route
object for each application route. Route
objects to the RouteCollection
object. RequestContext
object, which saves the current request context information. UrlMatcher
object by passing the RouteCollection
object and the RequestContext
object. Let's go ahead and define a very basic foo
route.
$foo_route = new Route( '/foo', array('controller' => 'FooController') );
Route
The first parameter to the constructor is the URI path and the second parameter is an array of custom properties to be returned when matching this specific route. Typically, it's a combination of controllers and methods that you call when this route is requested.
Next let’s take a look at parameterized routing.
$foo_placeholder_route = new Route( '/foo/{id}', array('controller' => 'FooController', 'method'=>'load'), array('id' => '[0-9]+') );
The above route can match foo/1
, foo/123
and other similar URIs. Note that we restricted the {id}
parameter to only numeric values, so it will not match a URI like foo/bar
because {id}
Parameters are provided as strings.
The next step is to add the route object we initialized in the previous section to the RouteCollection
object.
$routes = new RouteCollection(); $routes->add('foo_route', $foo_route); $routes->add('foo_placeholder_route', $foo_placeholder_route);
正如您所看到的,这非常简单,您只需要使用 RouteCollection
对象的 add
方法来添加路由对象。 add
方法的第一个参数是路由名称,第二个参数是路由对象本身。
RequestContext
对象接下来,我们需要初始化RequestContext
对象,该对象保存当前请求上下文信息。当我们初始化 UrlMatcher
对象时,我们将需要这个对象,因为我们稍后会详细介绍它。
$context = new RequestContext(); $context->fromRequest(Request::createFromGlobals());
UrlMatcher
对象最后,我们需要初始化 UrlMatcher
对象以及路由和上下文信息。
// Init UrlMatcher object $matcher = new UrlMatcher($routes, $context);
现在,我们拥有了可以匹配路线的一切。
这是 UrlMatcher
对象的 match
方法,它允许您将任何路由与一组预定义路由进行匹配。
match
方法将 URI 作为其第一个参数,并尝试将其与预定义的路由进行匹配。如果找到该路由,它将返回与该路由关联的自定义属性。另一方面,如果没有与当前 URI 关联的路由,它会抛出 ResourceNotFoundException
异常。
$parameters = $matcher->match($context->getPathInfo());
在我们的例子中,我们通过从 $context
对象获取当前 URI 来提供它。因此,如果您访问 https://your-domain/basic_routes.php/foo URL,则 $context->getPathInfo()
返回 foo
,并且我们已经为 foo
URI 定义了一条路由,因此它应该返回以下内容。
Array ( [controller] => FooController [_route] => foo_route )
现在,让我们继续访问 http://your-domain/basic_routes.php/foo/123 URL 来测试参数化路由。
Array ( [controller] => FooController [method] => load [id] => 123 [_route] => foo_placeholder_route )
如果您可以看到 id
参数与适当的值 123
绑定,则说明有效。
接下来,让我们尝试访问不存在的路由,例如 http://your-domain/basic_routes.php/unknown-route,您应该会看到以下消息。
No routes found for "/unknown-route".
这就是如何使用 match
方法查找路由。
除此之外,您还可以使用路由组件在应用程序中生成链接。提供了 RouteCollection
和 RequestContext
对象,UrlGenerator
允许您为特定路由构建链接。
$generator = new UrlGenerator($routes, $context); $url = $generator->generate('foo_placeholder_route', array( 'id' => 123, ));
generate
方法的第一个参数是路由名称,第二个参数是数组,如果是参数化路由,则可以包含参数。上面的代码应该生成 /basic_routes.php/foo/123 URL。
在上一节中,我们使用 Route
和 RouteCollection
对象构建了自定义路由。事实上,路由组件提供了不同的方式供您选择来实例化路由。您可以从各种加载器中进行选择,例如 YamlFileLoader
、XmlFileLoader
和 PhpFileLoader
。
在本节中,我们将通过 YamlFileLoader
加载器来了解如何从 YAML 文件加载路由。
继续创建包含以下内容的 routes.yaml 文件。
foo_route: path: /foo controller: App\Controller\FooController::index methods: GET foo_placeholder_route: path: /foo/{id} controller: App\Controller\FooController::load methods: GET requirements: id: '[0-9]+'
接下来,继续使用以下内容创建 load_routes_from_yaml.php 文件。
load('routes.yaml'); // Init RequestContext object $context = new RequestContext(); $context->fromRequest(Request::createFromGlobals()); // Init UrlMatcher object $matcher = new UrlMatcher($routes, $context); // Find the current route $parameters = $matcher->match($context->getPathInfo()); // How to generate a SEO URL $generator = new UrlGenerator($routes, $context); $url = $generator->generate('foo_placeholder_route', array( 'id' => 123, )); echo ''; print_r($parameters); echo 'Generated URL: ' . $url; exit; } catch (ResourceNotFoundException $e) { echo $e->getMessage(); }在这种情况下唯一不同的是我们初始化路由的方式!
$fileLocator = new FileLocator(array(__DIR__)); $loader = new YamlFileLoader($fileLocator); $routes = $loader->load('routes.yaml');我们使用
YamlFileLoader
加载器从 routes.yaml 文件加载路由,而不是直接在 PHP 本身中对其进行初始化。除此之外,一切都是相同的,并且应该产生与 basic_routes.php 文件相同的结果。一体化路由器
在本节中,我们将介绍
Router
类,它允许您使用更少的代码行快速设置路由。继续制作包含以下内容的 all_in_one_router.php 文件。
<?php require_once './vendor/autoload.php'; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Router; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Generator\UrlGenerator; use Symfony\Component\Config\FileLocator; use Symfony\Component\Routing\Loader\YamlFileLoader; use Symfony\Component\Routing\Exception\ResourceNotFoundException; try { $fileLocator = new FileLocator(array(__DIR__)); $requestContext = new RequestContext(); $requestContext->fromRequest(Request::createFromGlobals()); $router = new Router( new YamlFileLoader($fileLocator), 'routes.yaml', array('cache_dir' => __DIR__.'/cache'), $requestContext ); // Find the current route $parameters = $router->match($requestContext->getPathInfo()); // How to generate a SEO URL $routes = $router->getRouteCollection(); $generator = new UrlGenerator($routes, $requestContext); $url = $generator->generate('foo_placeholder_route', array( 'id' => 123, )); echo '<pre class="brush:php;toolbar:false">'; print_r($parameters); echo 'Generated URL: ' . $url; exit; } catch (ResourceNotFoundException $e) { echo $e->getMessage(); }一切都几乎相同,除了我们实例化了
Router
对象以及必要的依赖项。$router = new Router( new YamlFileLoader($fileLocator), 'routes.yaml', array('cache_dir' => __DIR__.'/cache'), $requestContext );完成后,您可以立即使用 Router 对象的
match
方法进行路由映射。$parameters = $router->match($requestContext->getPathInfo());此外,您还需要使用 Router 对象的
getRouteCollection
方法来获取路由。$routes = $router->getRouteCollection();将路由创建为注释:推荐方式
在本节中,我们将讨论如何实现基于注释的路由。它正在成为在不同框架之间定义路由的最流行的方法之一。
在我们继续实现基于注释的路由之前,我们需要安装几个软件包。让我们快速完成此操作,如以下代码片段所示。
$composer require symfony/framework-bundle $composer require doctrine/annotations $composer require doctrine/cache如您所见,我们安装了三个不同的组件。
在您的 composer.json 文件中,添加以下内容:
"autoload": { "psr-4": { "App\\": "app/" } }现在,运行以下命令。
$composer dump-autoload现在,我们准备好文件了。
继续创建包含以下内容的 index.php 文件。
load(__DIR__ . '/src/Controller/'); $context = new RequestContext(); $context->fromRequest(Request::createFromGlobals()); $matcher = new UrlMatcher($routes, $context); $parameters = $matcher->match($context->getPathInfo()); $controllerInfo = explode('::',$parameters['_controller']); $controller = new $controllerInfo[0]; $action = $controllerInfo[1]; $controller->$action();现在,让我们在 src/Controller/FooController.php 中创建包含以下内容的控制器文件。
<?php namespace App\Controller; use Symfony\Component\Routing\Annotation\Route; class DefaultController { /** * @Route("/",name="index") */ public function index() { echo "Index action"; } /** * @Route("/hello",name="hello") */ public function hello() { echo "Hello action"; } }您可能已经注意到,我们以注释的形式为每个方法定义了路由。这种方法的好处是,它允许您在与这些路由关联的控制器的代码旁边定义路由。
继续访问 https://your-domain/index.php/ URL。根据以下路由配置,它应该调用
index
方法。/** * @Route("/",name="index") */另一方面,如果您尝试访问 http://your-domain/index.php/hello URL,它应该调用
DefaultController
控制器的hello
方法类。这就是基于注释的路由的工作原理!
结论
继续探索路由组件中可用的其他选项。
今天,我们探索了 Symfony 路由组件,它使得在 PHP 应用程序中实现路由变得轻而易举。在此过程中,我们创建了一些示例来演示路由组件的各个方面。
The above is the detailed content of Set up routing in PHP applications using Symfony routing component. For more information, please follow other related articles on the PHP Chinese website!