Monday, May 04, 2015

[Symfony] Routing


By default, the routing configuration file in a Symfony application is located at app/config/routing.yml.

You can get the locate of routing.yml by check the app/config/config.yml:
framework:
    router:
           resource: "%kernel.root_dir%/config/routing.yml"
To make the encapsulation stronger, I do recommend you add your own routes in the bundle's routing.yml file:

my_website:
    resource: "@AppBundle/Resources/config/routing.yml"
    prefix:   / 


A common pitfall when defining routes is that routes have their precedence. The earlier a route appears, the earlier it will be matched. In other words, if the routes are not arranged properly, weird, difficult to debug problems will occur.

A route reads like the following in the routing file:
route_name1:
    path: /path/query
defaults:
    _controller: bundle:controller:action
    _format: html              #json
    template: ‘path/to/template.html/twig’
para1: val1
para2: val2
_method: [POST]
requirements:
     _locale:  en|fr
     _format:  html|rss
     year:     \d+
     condition: "context.getMethod() in ['GET', 'HEAD'] and request.headers.get('User-Agent') matches '/firefox/i'"

Special Routing Parameters

As you've seen, each routing parameter or default value is eventually available as an argument in the controller method. Additionally, there are three parameters that are special: each adds a unique piece of functionality inside your application:

_controller
    This parameter is used to determine which controller is executed when the route is matched. It
uses a simple string pattern called the logical controller name, which Symfony maps to a specific PHP method and class. The pattern has three parts, each separated by a colon:
   bundle:controller:action
    For example, a _controller value of AppBundle:Blog:show means:
       AppBundle => BlogController => showAction
_format
    Used to set the request format.
_locale
    Used to set the locale on the request.


To visualize and get detailed information about your routes, execute the command by running the following from the root of your project.:
$ php app/console debug:router

Likewise, if you want to test whether a URL matches a given route, you can use the router:match console command:
$ php app/console router:match /blog/my-latest-post  

Generating URLs from a Template

To generate a URL from within a template using a template helper function:

    <a href="{{ path('blog_show', {'slug': 'my-blog-post'}) }}">
      Read this blog post.
    </a>
   

Use the url() function to an absolute URL


    <a href="{{ url('blog_show', {'slug': 'my-blog-post'}) }}">
      Read this blog post.
    </a>
      


Reference:

symfony routing 

No comments: