Home Backend Development PHP Tutorial Getting Started with Symfony2 Route Annotations

Getting Started with Symfony2 Route Annotations

Feb 19, 2025 pm 01:24 PM

Getting Started with Symfony2 Route Annotations

Core points

  • Symfony2's SensioFrameworkExtraBundle allows developers to route configuration directly in the controller using annotations, providing a convenient alternative.
  • Routing annotations in Symfony2 make routing configuration more modular, and each route is directly defined in its corresponding controller operations, making the code easier to understand and maintain.
  • Annotations allow detailed routing configurations, including setting URL default parameters, adding requirements, enforcing HTTP methods or schemes, and enforcing hostnames.
  • While using annotations may make controller operations more complicated, as they now include routing configurations, this can be mitigated by keeping routing simple and well documented.

The standard Symfony 2 distribution contains a practical bundle called SensioFrameworkExtraBundle, which implements many powerful features, especially the ability to use annotations directly in the controller.

This article aims to introduce a convenient alternative to controller configuration, and is not a mandatory way of annotation. The best approach depends on the specific scenario requirements.

Symfony 2 manages all routing for applications with powerful built-in components: routing components. Basically, the route maps the URL to the controller action. Since Symfony is designed to be modular, a file is specially set up for this: routing.yml, located in app > config > routing.yml.

To understand how to define routes using annotations, let's take a simple blog application as an example.

Step 1: Create a homepage route

We link the

path to an operation of /. HomeController

No annotation method

In

: app/config/routing.yml

blog_front_homepage:
  path : /
  defaults:  { _controller: BlogFrontBundle:Home:index }
Copy after login
Copy after login
Copy after login
In

: src/Blog/FrontBundle/Controller/HomeController.php

<?php namespace Blog\FrontBundle\Controller;

class HomeController
{
    public function indexAction()
    {
        //... 创建并返回一个 Response 对象
    } 
}
Copy after login
Copy after login
Copy after login
In

, we declare a simple routing.yml routing configuration with two parameters: the path and the controller operation to be located. The controller itself does not require any special settings. blog_front_homepage

Using annotations

In

: app/config/routing.yml

blog_front:
    resource: "@BlogFrontBundle/Controller/"
    type:     annotation
    prefix:   /
Copy after login
Copy after login
Copy after login
Copy after login
In

: src/Blog/FrontBundle/Controller/HomeController.php

<?php 
namespace Blog\FrontBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class HomeController
{
    /**
     * @Route("/", name="blog_home_index")
     */
    public function indexAction() { /* ... */ }
}
Copy after login
Copy after login
Copy after login

Centre: routing.yml

  • resource Specify the controller to affect
  • type Define how to declare routes
  • prefix Define prefixes for all operations in the controller class (optional)

More important is how the controller is built. First, we must call the relevant class of SensioFrameworkExtraBundle: use SensioBundleFrameworkExtraBundleConfigurationRoute;. Then we can implement the route and its parameters: here only the path and name (we will see all the operations that can be performed later): @Route("/", name="blog_homepage").

One might think: "We know how to overwrite the controller with the routing layer, so what's the point? Ultimately, more code is needed to get the same result." At least for the moment.

Step 2: Add article page route

No annotation method

In app/config/routing.yml:

blog_front_homepage:
  path : /
  defaults:  { _controller: BlogFrontBundle:Home:index }
Copy after login
Copy after login
Copy after login

In src/Blog/FrontBundle/Controller/HomeController.php:

<?php namespace Blog\FrontBundle\Controller;

class HomeController
{
    public function indexAction()
    {
        //... 创建并返回一个 Response 对象
    } 
}
Copy after login
Copy after login
Copy after login

Using annotations

In app/config/routing.yml:

blog_front:
    resource: "@BlogFrontBundle/Controller/"
    type:     annotation
    prefix:   /
Copy after login
Copy after login
Copy after login
Copy after login

In src/Blog/FrontBundle/Controller/HomeController.php:

<?php 
namespace Blog\FrontBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class HomeController
{
    /**
     * @Route("/", name="blog_home_index")
     */
    public function indexAction() { /* ... */ }
}
Copy after login
Copy after login
Copy after login

Note: routing.yml No changes are required. Now you can see at a glance which operation is being called from routing mode.

If you want all operations in the controller to be prefixed, such as /admin, you can remove the routing.yml key from prefix and add an extra @Route to the top of the class Note:

In app/config/routing.yml:

blog_front_homepage:
  path : /
  defaults:  { _controller: BlogFrontBundle:Home:index }

blog_front_article:
  path : /article/{slug}
  defaults:  { _controller: BlogFrontBundle:Home:showArticle }
Copy after login

In src/Blog/AdminBundle/Controller/AdminController.php:

<?php // namespace & uses...

class HomeController
{
    public function indexAction() { /* ... */ }

    public function showArticleAction($slug) { /* ... */ }
}
Copy after login

Step 3: Additional routing configuration

Set URL default parameters

Chemism: defaults = { "key" = "value" }.

blog_front:
    resource: "@BlogFrontBundle/Controller/"
    type:     annotation
    prefix:   /
Copy after login
Copy after login
Copy after login
Copy after login

The slug placeholder is no longer required by adding defaults to the {slug} key. The URL /article will match this route, and the value of the slug parameter will be set to hello. The URL /blog/world will also match and set the value of the page parameter to world.

Add requirements

Chemism: requirements = { "key" = "value" }.

<?php // namespace & uses...

class HomeController
{
    /**
     * @Route("/", name="blog_home_index")
     */
    public function indexAction() { /* ... */ }

    /**
     * @Route("/article/{slug}", name="blog_home_show_article")
     */
    public function showArticleAction($slug) { /* ... */ }
}
Copy after login

We can use regular expressions to define requirements for the slug key, and clearly define the value of {slug} must consist of only alphabetical characters. In the following example, we do the exact same thing with the number:

blog_front: ...

blog_admin:
    resource: "@BlogAdminBundle/Controller/"
    type:     annotation
Copy after login

Enforce HTTP method

Chemism: methods = { "request method" }.

blog_front_homepage:
  path : /
  defaults:  { _controller: BlogFrontBundle:Home:index }
Copy after login
Copy after login
Copy after login

We can also match according to the methods of incoming requests (such as GET, POST, PUT, DELETE). Remember that if no method is specified, the route will match any method.

Enforce HTTP Solution

Chemism: schemes = { "protocol" }.

<?php namespace Blog\FrontBundle\Controller;

class HomeController
{
    public function indexAction()
    {
        //... 创建并返回一个 Response 对象
    } 
}
Copy after login
Copy after login
Copy after login

In this case, we want to ensure that the route is accessed through the HTTPS protocol.

Enforce hostname

Chemism: host = "myhost.com".

blog_front:
    resource: "@BlogFrontBundle/Controller/"
    type:     annotation
    prefix:   /
Copy after login
Copy after login
Copy after login
Copy after login

We can also match based on HTTP hosts. This will only match if the host is myblog.com.

Step 4: Practice

Now we can build a reliable routing structure, assuming we have to create the correct route for the operation of deleting articles in AdminController.php. We need:

  • Define the path as /admin/delete/article/{id};
  • Define the name as blog_admin_delete_article;
  • Define the requirement of the id key as numeric only;
  • Defines the GET request method.

The answer is as follows:

<?php 
namespace Blog\FrontBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class HomeController
{
    /**
     * @Route("/", name="blog_home_index")
     */
    public function indexAction() { /* ... */ }
}
Copy after login
Copy after login
Copy after login

Final Thoughts

As you can see, managing routing with annotations is easy to write, read and maintain. It also has the advantage of concentrating both code and configuration in one file: the controller class.

Do you use annotations or standard configuration? Which one do you prefer and why?

Symfony2 Routing Annotation FAQs (FAQs)

(The FAQs part is omitted here because this part of the content does not match the pseudo-original goal and is too long. If necessary, a pseudo-original request for the FAQs part can be made separately.)

The above is the detailed content of Getting Started with Symfony2 Route Annotations. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles