


Set up routing in PHP applications using Symfony routing component
Sep 03, 2023 pm 10:37 PMWhat 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
方法的第一個參數(shù)是路由名稱,第二個參數(shù)是路由對象本身。
初始化 RequestContext
對象
接下來,我們需要初始化RequestContext
對象,該對象保存當前請求上下文信息。當我們初始化 UrlMatcher
對象時,我們將需要這個對象,因為我們稍后會詳細介紹它。
$context = new RequestContext(); $context->fromRequest(Request::createFromGlobals());
初始化 UrlMatcher
對象
最后,我們需要初始化 UrlMatcher
對象以及路由和上下文信息。
// Init UrlMatcher object $matcher = new UrlMatcher($routes, $context);
現(xiàn)在,我們擁有了可以匹配路線的一切。
如何匹配路由
這是 UrlMatcher
對象的 match
方法,它允許您將任何路由與一組預(yù)定義路由進行匹配。
match
方法將 URI 作為其第一個參數(shù),并嘗試將其與預(yù)定義的路由進行匹配。如果找到該路由,它將返回與該路由關(guān)聯(lián)的自定義屬性。另一方面,如果沒有與當前 URI 關(guān)聯(lián)的路由,它會拋出 ResourceNotFoundException
異常。
$parameters = $matcher->match($context->getPathInfo());
在我們的例子中,我們通過從 $context
對象獲取當前 URI 來提供它。因此,如果您訪問 https://your-domain/basic_routes.php/foo URL,則 $context->getPathInfo()
返回 foo
,并且我們已經(jīng)為 foo
URI 定義了一條路由,因此它應(yīng)該返回以下內(nèi)容。
Array ( [controller] => FooController [_route] => foo_route )
現(xiàn)在,讓我們繼續(xù)訪問 http://your-domain/basic_routes.php/foo/123 URL 來測試參數(shù)化路由。
Array ( [controller] => FooController [method] => load [id] => 123 [_route] => foo_placeholder_route )
如果您可以看到 id
參數(shù)與適當?shù)闹?123
綁定,則說明有效。
接下來,讓我們嘗試訪問不存在的路由,例如 http://your-domain/basic_routes.php/unknown-route,您應(yīng)該會看到以下消息。
No routes found for "/unknown-route".
這就是如何使用 match
方法查找路由。
除此之外,您還可以使用路由組件在應(yīng)用程序中生成鏈接。提供了 RouteCollection
和 RequestContext
對象,UrlGenerator
允許您為特定路由構(gòu)建鏈接。
$generator = new UrlGenerator($routes, $context); $url = $generator->generate('foo_placeholder_route', array( 'id' => 123, ));
generate
方法的第一個參數(shù)是路由名稱,第二個參數(shù)是數(shù)組,如果是參數(shù)化路由,則可以包含參數(shù)。上面的代碼應(yīng)該生成 /basic_routes.php/foo/123 URL。
從 YAML 文件加載路由
在上一節(jié)中,我們使用 Route
和 RouteCollection
對象構(gòu)建了自定義路由。事實上,路由組件提供了不同的方式供您選擇來實例化路由。您可以從各種加載器中進行選擇,例如 YamlFileLoader
、XmlFileLoader
和 PhpFileLoader
。
在本節(jié)中,我們將通過 YamlFileLoader
加載器來了解如何從 YAML 文件加載路由。
路由 YAML 文件
繼續(xù)創(chuàng)建包含以下內(nèi)容的 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]+'
示例文件
接下來,繼續(xù)使用以下內(nèi)容創(chuàng)建 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 本身中對其進行初始化。除此之外,一切都是相同的,并且應(yīng)該產(chǎn)生與 basic_routes.php 文件相同的結(jié)果。一體化路由器
在本節(jié)中,我們將介紹
Router
類,它允許您使用更少的代碼行快速設(shè)置路由。繼續(xù)制作包含以下內(nèi)容的 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();將路由創(chuàng)建為注釋:推薦方式
在本節(jié)中,我們將討論如何實現(xiàn)基于注釋的路由。它正在成為在不同框架之間定義路由的最流行的方法之一。
在我們繼續(xù)實現(xiàn)基于注釋的路由之前,我們需要安裝幾個軟件包。讓我們快速完成此操作,如以下代碼片段所示。
$composer require symfony/framework-bundle $composer require doctrine/annotations $composer require doctrine/cache如您所見,我們安裝了三個不同的組件。
在您的 composer.json 文件中,添加以下內(nèi)容:
"autoload": { "psr-4": { "App\\": "app/" } }現(xiàn)在,運行以下命令。
$composer dump-autoload現(xiàn)在,我們準備好文件了。
繼續(xù)創(chuàng)建包含以下內(nèi)容的 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();現(xiàn)在,讓我們在 src/Controller/FooController.php 中創(chuàng)建包含以下內(nèi)容的控制器文件。
<?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"; } }您可能已經(jīng)注意到,我們以注釋的形式為每個方法定義了路由。這種方法的好處是,它允許您在與這些路由關(guān)聯(lián)的控制器的代碼旁邊定義路由。
繼續(xù)訪問 https://your-domain/index.php/ URL。根據(jù)以下路由配置,它應(yīng)該調(diào)用
index
方法。/** * @Route("/",name="index") */另一方面,如果您嘗試訪問 http://your-domain/index.php/hello URL,它應(yīng)該調(diào)用
DefaultController
控制器的hello
方法類。這就是基于注釋的路由的工作原理!
結(jié)論
繼續(xù)探索路由組件中可用的其他選項。
今天,我們探索了 Symfony 路由組件,它使得在 PHP 應(yīng)用程序中實現(xiàn)路由變得輕而易舉。在此過程中,我們創(chuàng)建了一些示例來演示路由組件的各個方面。
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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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

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

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:

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

How to prevent file upload vulnerabilities from being exploited in PHP applications Introduction: In modern web applications, file upload functionality is a common requirement. However, if not properly implemented and verified, the file upload functionality can become an entry point for hackers, leading to serious security vulnerabilities. This article will describe how to prevent the exploitation of file upload vulnerabilities in PHP applications and provide some code examples to help you strengthen the security of your applications. 1. The principle of the file upload vulnerability The principle of the file upload vulnerability is that the attacker exploits the vulnerability point.
