


Set up routing in PHP applications using Symfony routing component
What is 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:
- Symfony routing component installation and configuration
- How to set up a basic route
- How to load routes from YAML file
- Create routes as comments: Recommended way
Installation and Configuration
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 ?>
Set up basic routing
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.
- Initialize the
Route
object for each application route. - Add all
Route
objects to theRouteCollection
object. - Initialize
RequestContext
object, which saves the current request context information. - Initialize the
UrlMatcher
object by passing theRouteCollection
object and theRequestContext
object.
Initialize routing objects for different routes
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.
Add all routing objects to the RouteCollection object
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。
从 YAML 文件加载路由
在上一节中,我们使用 Route
和 RouteCollection
对象构建了自定义路由。事实上,路由组件提供了不同的方式供您选择来实例化路由。您可以从各种加载器中进行选择,例如 YamlFileLoader
、XmlFileLoader
和 PhpFileLoader
。
在本节中,我们将通过 YamlFileLoader
加载器来了解如何从 YAML 文件加载路由。
路由 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(); }Copy after login
在这种情况下唯一不同的是我们初始化路由的方式!
$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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The secret weapon to accelerate PHP application deployment: Deployer. Quick and efficient deployment of applications has always been one of the important tasks of the software development team. In PHP development, deploying an application usually involves multiple steps such as uploading files, updating code, and configuring the environment. In order to simplify and accelerate this process, modern development tools and technologies are gradually introduced, and one of the widely recognized secret weapons is Deployer. Deployer is a PHP library for automated application deployment

How to use Deployer to deploy PHP applications In the modern software development process, automated deployment is becoming more and more important. Deployer is a simple and powerful PHP deployment tool, which can help us deploy PHP applications easily. This article will introduce how to use Deployer to deploy PHP applications and provide some code examples. 1. Install Deployer First, we need to install Deployer through Composer. Run the following command in the command line

What are Symfony routing components? Symfony routing component is a very popular routing component that is adapted from several frameworks and provides a lot of flexibility if you wish 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, 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 through practical examples the various options this component has for routing configuration. In this article, you will learn: Installation and configuration of the Symfony routing component How to set up a basic route How to load a route from a YAML file Create a route as an annotation:

How to use Memcache to improve the performance and availability of PHP applications? Introduction: With the rapid development of Internet applications and the increase in user visits, improving the performance and availability of applications has become one of the issues that developers need to solve urgently. Among them, using cache is a common optimization method. Memcache is a commonly used caching technology that can significantly improve application performance and availability. This article will introduce how to use Memcache in PHP applications and give specific code examples. Install

Efficient batch deployment of PHP applications: Use Deployer Introduction: With the rise of cloud computing, containerization and microservice architecture, the deployment of modern applications has become increasingly complex and cumbersome. Especially in situations where a development team needs to deploy multiple PHP applications frequently, manually deploying each application is time-consuming and error-prone. To solve this problem, we can use the Deployer tool to automate and simplify the deployment process of PHP applications. In this article, we will introduce the Deployer

Application of security testing tools to PHP applications With the development of the Internet, the use of PHP applications in the network is becoming more and more common. However, security threats are also increasing. To ensure the security of PHP applications, developers need to conduct effective security testing. This article will introduce some commonly used security testing tools and provide relevant code examples to help developers better protect their applications. Static code analysis tools Static code analysis tools can check potential vulnerabilities in source code and provide relevant

In recent years, as web applications have become more and more complex, how to optimize the response time of web applications has become a hot topic. Among them, caching technology is an important means to optimize response time. In this article, we will detail how to optimize PHP application response time through caching technology. 1. Why is caching needed? When a user accesses a web application, the web server parses the PHP script into HTML code and returns it to the user's browser. However, if the PHP script is very complex, before returning HTM

Memcached is an open source, easy-to-deploy and lightweight distributed caching system that is widely used in web application caching. It can be used to resolve database access bottlenecks often used in larger web applications, while also improving application performance. In this article, we will discuss how to use Memcached to optimize caching for PHP applications. Using Caching Using caching can effectively reduce the number of queries to the database in a web application. Because if a query result already exists
