[ Index ]
 

Code source de Symfony 1.0.0

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/doc/ -> 09-Links-and-the-Routing-System.txt (source)

   1  Chapter 9 - Links And The Routing System
   2  ========================================
   3  
   4  Links and URLs deserve particular treatment in a web application framework. This is because the unique entry point of the application (the front controller) and the use of helpers in templates allow for a complete separation between the way URLs work and their appearance. This is called routing. More than a gadget, routing is a useful tool to make web applications even more user-friendly and secure. This chapter will tell you everything you need to know to handle URLs in your symfony applications:
   5  
   6    * What the routing system is and how it works
   7    * How to use link helpers in templates to enable routing of outgoing URLs
   8    * How to configure the routing rules to change the appearance of URLs
   9  
  10  You will also find a few tricks for mastering routing performance and adding finishing touches.
  11  
  12  What Is Routing?
  13  ----------------
  14  
  15  Routing is a mechanism that rewrites URLs to make them more user-friendly. But to understand why this is important, you must first take a few minutes to think about URLs.
  16  
  17  ### URLs As Server Instructions
  18  
  19  URLs carry information from the browser to the server required to enact an action as desired by the user. For instance, a traditional URL contains the file path to a script and some parameters necessary to complete the request, as in this example:
  20  
  21      http://www.example.com/web/controller/article.php?id=123456&format_code=6532
  22  
  23  This URL conveys information about the application's architecture and database. Developers usually hide the application's infrastructure in the interface (for instance, they choose page titles like "Personal profile page" rather than "QZ7.65"). Revealing vital clues to the internals of the application in the URL contradicts this effort and has serious drawbacks:
  24  
  25    * The technical data appearing in the URL creates potential security breaches. In the preceding example, what happens if an ill-disposed user changes the value of the `id` parameter? Does this mean the application offers a direct interface to the database? Or what if the user tries other script names, like `admin.php`, just for fun? All in all, raw URLs offer an easy way to hack an application, and managing security is almost impossible with them.
  26    * The unintelligibility of URLs makes them disturbing wherever they appear, and they dilute the impact of the surrounding content. And nowadays, URLs don't appear only in the address bar. They appear when a user hovers the mouse over a link, as well as in search results. When users look for information, you want to give them easily understandable clues regarding what they found, rather than a confusing URL such as the one shown in Figure 9-1.
  27  
  28  Figure 9-1 - URLs appear in many places, such as in search results
  29  
  30  ![URLs appear in many places, such as in search results](/images/book/F0901.png "URLs appear in many places, such as in search results")
  31  
  32    * If one URL has to be changed (for instance, if a script name or one of its parameters is modified), every link to this URL must be changed as well. It means that modifications in the controller structure are heavyweight and expensive, which is not ideal in agile development.
  33  
  34  And it could be much worse if symfony didn't use the front controller paradigm; that is, if the application contained many scripts accessible from the Internet, in many directories, such as these:
  35  
  36      http://www.example.com/web/gallery/album.php?name=my%20holidays
  37      http://www.example.com/web/weblog/public/post/list.php
  38      http://www.example.com/web/general/content/page.php?name=about%20us
  39  
  40  In this case, developers would need to match the URL structure with the file structure, resulting in a maintenance nightmare when either structure changed.
  41  
  42  ### URLs As Part of the Interface
  43  
  44  The idea behind routing is to consider the URL as part of the interface. The application can format a URL to bring information to the user, and the user can use the URL to access resources of the application.
  45  
  46  This is possible in symfony applications, because the URL presented to the end user is unrelated to the server instruction needed to perform the request. Instead, it is related to the resource requested, and it can be formatted freely. For instance, symfony can understand the following URL and have it display the same page as the first URL shown in this chapter:
  47  
  48      http://www.example.com/articles/finance/2006/activity-breakdown.html
  49  
  50  The benefits are immense:
  51  
  52    * URLs actually mean something, and they can help the users decide if the page behind a link contains what they expect. A link can contain additional details about the resource it returns. This is particularly useful for search engine results. Additionally, URLs sometimes appear without any mention of the page title (think about when you copy a URL in an e-mail message), and in this case, they must mean something on their own. See Figure 9-2 for an example of a user-friendly URL.
  53  
  54  Figure 9-2 - URLs can convey additional information about a page, like the publication date
  55  
  56  ![URLs can convey additional information about a page, like the publication date](/images/book/F0902.png "URLs can convey additional information about a page, like the publication date")
  57  
  58    * URLs written in paper documents are easier to type and remember. If your company website appears as `http://www.example.com/controller/web/index.jsp?id=ERD4` on your business card, it will probably not receive many visits.
  59    * The URL can become a command-line tool of its own, to perform actions or retrieve information in an intuitive way. Applications offering such a possibility are faster to use for power users.
  60  
  61          // List of results: add a new tag to narrow the list of results
  62          http://del.icio.us/tag/symfony+ajax
  63          // User profile page: change the name to get another user profile
  64          http://www.askeet.com/user/francois
  65  
  66    * You can change the URL formatting and the action name/parameters independently, with a single modification. It means that you can develop first, and format the URLs afterwards, without totally messing up your application.
  67    * Even when you reorganize the internals of an application, the URLs can remain the same for the outside world. It makes URLs persistent, which is a must because it allows bookmarking on dynamic pages.
  68    * Search engines tend to skip dynamic pages (ending with `.php`, `.asp`, and so on) when they index websites. So you can format URLs to have search engines think they are browsing static content, even when they meet a dynamic page, thus resulting in better indexing of your application pages.
  69    * It is safer. Any unrecognized URL will be redirected to a page specified by the developer, and users cannot browse the web root file structure by testing URLs. The actual script name called by the request, as well as its parameters, is hidden.
  70  
  71  The correspondence between the URLs presented to the user and the actual script name and request parameters is achieved by a routing system, based on patterns that can be modified through configuration.
  72  
  73  >**NOTE**
  74  >How about assets? Fortunately, the URLs of assets (images, style sheets, and JavaScript) don't appear much during browsing, so there is no real need for routing for those. In symfony, all assets are located under the `web/` directory, and their URL matches their location in the file system. However, you can manage dynamic assets (handled by actions) by using a generated URL inside the asset helper. For instance, to display a dynamically generated image, use `image_tag(url_for('captcha/image?key='.$key))`.
  75  
  76  ### How It Works
  77  
  78  Symfony disconnects the external URL and its internal URI. The correspondence between the two is made by the routing system. To make things easy, symfony uses a syntax for internal URIs very similar to the one of regular URLs. Listing 9-1 shows an example.
  79  
  80  Listing 9-1 - External URL and Internal URI
  81  
  82      // Internal URI syntax
  83      <module>/<action>[?param1=value1][&param2=value2][&param3=value3]...
  84  
  85      // Example internal URI, which never appears to the end user
  86      article/permalink?year=2006&subject=finance&title=activity-breakdown
  87  
  88      // Example external URL, which appears to the end user
  89      http://www.example.com/articles/finance/2006/activity-breakdown.html
  90  
  91  The routing system uses a special configuration file, called `routing.yml`, in which you can define routing rules. Consider the rule shown in Listing 9-2. It defines a pattern that looks like `articles/*/*/*` and names the pieces of content matching the wildcards.
  92  
  93  Listing 9-2 - A Sample Routing Rule
  94  
  95      article_by_title:
  96        url:    articles/:subject/:year/:title.html
  97        param:  { module: article, action: permalink }
  98  
  99  Every request sent to a symfony application is first analyzed by the routing system (which is simple because every request in handled by a single front controller). The routing system looks for a match between the request URL and the patterns defined in the routing rules. If a match is found, the named wildcards become request parameters and are merged with the ones defined in the `param:` key. See how it works in Listing 9-3.
 100  
 101  Listing 9-3 - The Routing System Interprets Incoming Request URLs
 102  
 103      // The user types (or clicks on) this external URL
 104      http://www.example.com/articles/finance/2006/activity-breakdown.html
 105  
 106      // The front controller sees that it matches the article_by_title rule
 107      // The routing system creates the following request parameters
 108        'module'  => 'article'
 109        'action'  => 'permalink'
 110        'subject' => 'finance'
 111        'year'    => '2006'
 112        'title'   => 'activity-breakdown'
 113  
 114  >**TIP**
 115  >The `.html` extension of the external URL is a simple decoration and is ignored by the routing system. Its sole interest is to makes dynamic pages look like static ones. You will see how to activate this extension in the "Routing Configuration" section later in this chapter.
 116  
 117  The request is then passed to the `permalink` action of the `article` module, which has all the required information in the request parameters to determine which article is to be shown.
 118  
 119  But the mechanism also must work the other way around. For the application to show external URLs in its links, you must provide the routing system with enough data to determine which rule to apply to it. You also must not write hyperlinks directly with `<a>` tags--this would bypass routing completely--but with a special helper, as shown in Listing 9-4.
 120  
 121  Listing 9-4 - The Routing System Formats Outgoing URLs in Templates
 122  
 123      [php]
 124      // The url_for() helper transforms an internal URI into an external URL
 125      <a href="<?php echo url_for('article/permalink?subject=finance&year=2006&title=activity-breakdown') ?>">click here</a>
 126  
 127      // The helper sees that the URI matches the article_by_title rule
 128      // The routing system creates an external URL out of it
 129       => <a href="http://www.example.com/articles/finance/2006/activity-breakdown.html">click here</a>
 130  
 131      // The link_to() helper directly outputs a hyperlink
 132      // and avoids mixing PHP with HTML
 133      <?php echo link_to(
 134        'click here',
 135        'article/permalink?subject=finance&year=2006&title=activity-breakdown'
 136      ) ?>
 137  
 138      // Internally, link_to() will make a call to url_for() so the result is the same
 139      => <a href="http://www.example.com/articles/finance/2006/activity-breakdown.html">click here</a>
 140  
 141  So routing is a two-way mechanism, and it works only if you use the `link_to()` helper to format all your links.
 142  
 143  URL Rewriting
 144  -------------
 145  
 146  Before getting deeper into the routing system, one matter needs to be clarified. In the examples given in the previous section, there is no mention of the front controller (`index.php` or `myapp_dev.php`) in the internal URIs. The front controller, not the elements of the application, decides the environment. So all the links must be environment-independent, and the front controller name can never appear in internal URIs.
 147  
 148  There is no script name in the examples of generated URLs either. This is because generated URLs don't contain any script name in the production environment by default. The `no_script_name` parameter of the `settings.yml` file precisely controls the appearance of the front controller name in generated URLs. Set it to `off`, as shown in Listing 9-5, and the URLs output by the link helpers will mention the front controller script name in every link.
 149  
 150  Listing 9-5 - Showing the Front Controller Name in URLs, in `apps/myapp/settings.yml`
 151  
 152      prod:
 153        .settings
 154          no_script_name:  off
 155  
 156  Now, the generated URLs will look like this:
 157  
 158      http://www.example.com/index.php/articles/finance/2006/activity-breakdown.html
 159  
 160  In all environments except the production one, the `no_script_name` parameter is set to `off` by default. So when you browse your application in the development environment, for instance, the front controller name always appears in the URLs.
 161  
 162      http://www.example.com/myapp_dev.php/articles/finance/2006/activity-breakdown.html
 163  
 164  In production, the `no_script_name` is set to `on`, so the URLs show only the routing information and are more user-friendly. No technical information appears.
 165  
 166      http://www.example.com/articles/finance/2006/activity-breakdown.html
 167  
 168  But how does the application know which front controller script to call? This is where URL rewriting comes in. The web server can be configured to call a given script when there is none in the URL.
 169  
 170  In Apache, this is possible once you have the `mod_rewrite` extension activated. Every symfony project comes with an `.htaccess` file, which adds `mod_rewrite` settings to your server configuration for the `web/` directory. The default content of this file is shown in Listing 9-6.
 171  
 172  Listing 9-6 - Default Rewriting Rules for Apache, in `myproject/web/.htaccess`
 173  
 174      <IfModule mod_rewrite.c>
 175        RewriteEngine On
 176  
 177        # we skip all files with .something
 178        RewriteCond %{REQUEST_URI} \..+$
 179        RewriteCond %{REQUEST_URI} !\.html$
 180        RewriteRule .* - [L]
 181  
 182        # we check if the .html version is here (caching)
 183        RewriteRule ^$ index.html [QSA]
 184        RewriteRule ^([^.]+)$ $1.html [QSA]
 185        RewriteCond %{REQUEST_FILENAME} !-f
 186  
 187        # no, so we redirect to our front web controller
 188        RewriteRule ^(.*)$ index.php [QSA,L]
 189      </IfModule>
 190  
 191  The web server inspects the shape of the URLs it receives. If the URL does not contain a suffix and if there is no cached version of the page available (Chapter 12 covers caching), then the request is handed to `index.php`.
 192  
 193  However, the `web/` directory of a symfony project is shared among all the applications and environments of the project. It means that there is usually more than one front controller in the web directory. For instance, a project having a `frontend` and a `backend` application, and a `dev` and `prod` environment, contains four front controller scripts in the `web/` directory:
 194  
 195      index.php         // frontend in prod
 196      frontend_dev.php  // frontend in dev
 197      backend.php       // backend in prod
 198      backend_dev.php   // backend in dev
 199  
 200  The mod_rewrite settings can specify only one default script name. If you set no_script_name to on for all the applications and environments, all URLs will be interpreted as requests to the `frontend` application in the `prod` environment. This is why you can have only one application with one environment taking advantage of the URL rewriting for a given project.
 201  
 202  >**TIP**
 203  >There is a way to have more than one application with no script name. Just create subdirectories in the web root, and move the front controllers inside them. Change the `SF_ROOT_DIR` constants definition accordingly, and create the `.htaccess` URL rewriting configuration that you need for each application.
 204  
 205  Link Helpers
 206  ------------
 207  
 208  Because of the routing system, you should use link helpers instead of regular `<a>` tags in your templates. Don't look at it as a hassle, but rather as an opportunity to keep your application clean and easy to maintain. Besides, link helpers offer a few very useful shortcuts that you don't want to miss.
 209  
 210  ### Hyperlinks, Buttons, and Forms
 211  
 212  You already know about the `link_to()` helper. It outputs an XHTML-compliant hyperlink, and it expects two parameters: the element that can be clicked and the internal URI of the resource to which it points. If, instead of a hyperlink, you want a button, use the `button_to()` helper. Forms also have a helper to manage the value of the `action` attribute. You will learn more about forms in the next chapter. Listing 9-7 shows some examples of link helpers.
 213  
 214  Listing 9-7 - Link Helpers for `<a>`, `<input>`, and `<form>` Tags
 215  
 216      [php]
 217      // Hyperlink on a string
 218      <?php echo link_to('my article', 'article/read?title=Finance_in_France') ?>
 219       => <a href="/routed/url/to/Finance_in_France">my article</a>
 220  
 221      // Hyperlink on an image
 222      <?php echo link_to(image_tag('read.gif'), 'article/read?title=Finance_in_France') ?>
 223       => <a href="/routed/url/to/Finance_in_France"><img src="/images/read.gif" /></a>
 224  
 225      // Button tag
 226      <?php echo button_to('my article', 'article/read?title=Finance_in_France') ?>
 227       => <input value="my article" type="button"onclick="document.location.href='/routed/url/to/Finance_in_France';" />
 228  
 229      // Form tag
 230      <?php echo form_tag('article/read?title=Finance_in_France') ?>
 231       => <form method="post" action="/routed/url/to/Finance_in_France" />
 232  
 233  Link helpers can accept internal URIs as well as absolute URLs (starting with `http://`, and skipped by the routing system) and anchors. Note that in real-world applications, internal URIs are built with dynamic parameters. Listing 9-8 shows examples of all these cases.
 234  
 235  Listing 9-8 - URLs Accepted by Link Helpers
 236  
 237      [php]
 238      // Internal URI
 239      <?php echo link_to('my article', 'article/read?title=Finance_in_France') ?>
 240       => <a href="/routed/url/to/Finance_in_France">my article</a>
 241  
 242      // Internal URI with dynamic parameters
 243      <?php echo link_to('my article', 'article/read?title='.$article->getTitle()) ?>
 244  
 245      // Internal URI with anchors
 246      <?php echo link_to('my article', 'article/read?title=Finance_in_France#foo') ?>
 247       => <a href="/routed/url/to/Finance_in_France#foo">my article</a>
 248  
 249      // Absolute URL
 250      <?php echo link_to('my article', 'http://www.example.com/foobar.html') ?>
 251       => <a href="http://www.example.com/foobar.html">my article</a>
 252  
 253  ### Link Helper Options
 254  
 255  As explained in Chapter 7, helpers accept an additional options argument, which can be an associative array or a string. This is true for link helpers, too, as shown in Listing 9-9.
 256  
 257  Listing 9-9 - Link Helpers Accept Additional Options
 258  
 259      [php]
 260      // Additional options as an associative array
 261      <?php echo link_to('my article', 'article/read?title=Finance_in_France', array(
 262        'class'  => 'foobar',
 263        'target' => '_blank'
 264      )) ?>
 265  
 266      // Additional options as a string (same result)
 267      <?php echo link_to('my article', 'article/read?title=Finance_in_France','class=foobar target=_blank') ?>
 268       => <a href="/routed/url/to/Finance_in_France" class="foobar" target="_blank">my article</a>
 269  
 270  You can also add one of the symfony-specific options for link helpers: `confirm` and `popup`. The first one displays a JavaScript confirmation dialog box when the link is clicked, and the second opens the link in a new window, as shown in Listing 9-10.
 271  
 272  Listing 9-10 - `'confirm'` and `'popup'` Options for Link Helpers
 273  
 274      [php]
 275      <?php echo link_to('delete item', 'item/delete?id=123', 'confirm=Are you sure?') ?>
 276       => <a onclick="return confirm('Are you sure?');"
 277             href="/routed/url/to/delete/123.html">add to cart</a>
 278  
 279      <?php echo link_to('add to cart', 'shoppingCart/add?id=100', 'popup=true') ?>
 280       => <a onclick="window.open(this.href);return false;"
 281             href="/fo_dev.php/shoppingCart/add/id/100.html">add to cart</a>
 282  
 283      <?php echo link_to('add to cart', 'shoppingCart/add?id=100', array(
 284        'popup' => array('Window title', 'width=310,height=400,left=320,top=0')
 285      )) ?>
 286       => <a onclick="window.open(this.href,'Window title','width=310,height=400,left=320,top=0');return false;"
 287             href="/fo_dev.php/shoppingCart/add/id/100.html">add to cart</a>
 288  
 289  These options can be combined.
 290  
 291  ### Fake GET and POST Options
 292  
 293  Sometimes web developers use GET requests to actually do a POST. For instance, consider the following URL:
 294  
 295      http://www.example.com/index.php/shopping_cart/add/id/100
 296  
 297  This request will change the data contained in the application, by adding an item to a shopping cart object, stored in the session or in a database. This URL can be bookmarked, cached, and indexed by search engines. Imagine all the nasty things that might happen to the database or to the metrics of a website using this technique. As a matter of fact, this request should be considered as a POST, because search engine robots do not do POST requests on indexing.
 298  
 299  Symfony provides a way to transform a call to a `link_to()` or `button_to()` helper into an actual POST. Just add a `post=true` option, as shown in Listing 9-11.
 300  
 301  Listing 9-11 - Making a Link Call a POST Request
 302  
 303      [php]
 304      <?php echo link_to('go to shopping cart', 'shoppingCart/add?id=100', 'post=true') ?>
 305       => <a onclick="f = document.createElement('form'); document.body.appendChild(f);
 306                      f.method = 'POST'; f.action = this.href; f.submit();return false;"
 307             href="/shoppingCart/add/id/100.html">go to shopping cart</a>
 308  
 309  This `<a>` tag has an `href` attribute, and browsers without JavaScript support, such as search engine robots, will follow the link doing the default GET. So you must also restrict your action to respond only to the POST method, by adding something like the following at the beginning of the action:
 310  
 311      [php]
 312      $this->forward404If($request->getMethod() != sfRequest::POST);
 313  
 314  Just make sure you don't use this option on links located in forms, since it generates its own `<form>` tag.
 315  
 316  It is a good habit to tag as POST the links that actually post data.
 317  
 318  ### Forcing Request Parameters As GET Variables
 319  
 320  According to your routing rules, variables passed as parameters to a `link_to()` are transformed into patterns. If no rule matches the internal URI in the `routing.yml` file, the default rule transforms `module/action?key=value` into `/module/action/key/value`, as shown in Listing 9-12.
 321  
 322  Listing 9-12 - Default Routing Rule
 323  
 324      [php]
 325      <?php echo link_to('my article', 'article/read?title=Finance_in_France') ?>
 326      => <a href="/article/read/title/Finance_in_France">my article</a>
 327  
 328  If you actually need to keep the GET syntax--to have request parameters passed under the ?key=value form--you should put the variables that need to be forced outside the URL parameter, in the query_string option. All the link helpers accept this option, as demonstrated in Listing 9-13.
 329  
 330  Listing 9-13 - Forcing GET Variables with the `query_string` Option
 331  
 332      [php]
 333      <?php echo link_to('my article', 'article/read?title=Finance_in_France', array(
 334        'query_string' => 'title=Finance_in_France'
 335      )) ?>
 336      => <a href="/article/read?title=Finance_in_France">my article</a>
 337  
 338  A URL with request parameters appearing as GET variables can be interpreted by a script on the client side, and by the `$_GET` and `$_REQUEST` variables on the server side.
 339  
 340  >**SIDEBAR**
 341  >Asset helpers
 342  >
 343  >Chapter 7 introduced the asset helpers `image_tag()`, `stylesheet_tag()`, and `javascript_include_ tag()`, which allow you to include an image, a style sheet, or a JavaScript file in the response. The paths to such assets are not processed by the routing system, because they link to resources that are actually located under the public web directory.
 344  >
 345  >You don't need to mention a file extension for an asset. Symfony automatically adds `.png`, `.js`, or `.css` to an image, JavaScript, or style sheet helper call. Also, symfony will automatically look for those assets in the `web/images/`, `web/js/`, and `web/css/` directories. Of course, if you want to include a specific file format or a file from a specific location, just use the full file name or the full file path as an argument. And don't bother to specify an `alt` attribute if your media file has an explicit name, since symfony will determine it for you.
 346  >
 347  >     [php]
 348  >     <?php echo image_tag('test') ?>
 349  >     <?php echo image_tag('test.gif') ?>
 350  >     <?php echo image_tag('/my_images/test.gif') ?>
 351  >      => <img href="/images/test.png" alt="Test" />
 352  >         <img href="/images/test.gif" alt="Test" />
 353  >         <img href="/my_images/test.gif" alt="Test" />
 354  >
 355  >To fix the size of an image, use the `size` attribute. It expects a width and a height in pixels, separated by an `x`.
 356  >
 357  >     [php]
 358  >     <?php echo image_tag('test', 'size=100x20')) ?>
 359  >      => <img href="/images/test.png" alt="Test" width="100" height="20"/>
 360  >
 361  >If you want the asset inclusion to be done in the `<head>` section (for JavaScript files and style sheets), you should use the `use_stylesheet()` and `use_javascript()` helpers in your templates, instead of the `_tag()` versions in the layout. They add the asset to the response, and these assets are included before the `</head>` tag is sent to the browser.
 362  
 363  ### Using Absolute Paths
 364  
 365  The link and asset helpers generate relative paths by default. To force the output to absolute paths, set the `absolute` option to `true`, as shown in Listing 9-14. This technique is useful for inclusions of links in an e-mail message, RSS feed, or API response.
 366  
 367  Listing 9-14 - Getting Absolute URLs Instead of Relative URLs
 368  
 369      [php]
 370      <?php echo url_for('article/read?title=Finance_in_France') ?>
 371       => '/routed/url/to/Finance_in_France'
 372      <?php echo url_for('article/read?title=Finance_in_France', true) ?>
 373       => 'http://www.example.com/routed/url/to/Finance_in_France'
 374  
 375      <?php echo link_to('finance', 'article/read?title=Finance_in_France') ?>
 376       => <a href="/routed/url/to/Finance_in_France">finance</a>
 377      <?php echo link_to('finance', 'article/read?title=Finance_in_France','absolute=true') ?>
 378       => <a href=" http://www.example.com/routed/url/to/Finance_in_France">finance</a>
 379  
 380      // The same goes for the asset helpers
 381      <?php echo image_tag('test', 'absolute=true') ?>
 382      <?php echo javascript_include_tag('myscript', 'absolute=true') ?>
 383  
 384  >**SIDEBAR**
 385  >The Mail helper
 386  >
 387  >Nowadays, e-mail-harvesting robots prowl about the Web, and you can't display an e-mail address on a website without becoming a spam victim within days. This is why symfony provides a `mail_to()` helper.
 388  >
 389  >The `mail_to()` helper takes two parameters: the actual e-mail address and the string that should be displayed. Additional options accept an `encode` parameter to output something pretty unreadable in HTML, which is understood by browsers but not by robots.
 390  >
 391  >     [php]
 392  >     <?php echo mail_to('myaddress@mydomain.com', 'contact') ?>
 393  >      => <a href="mailto:myaddress@mydomain.com'>contact</a>
 394  >     <?php echo mail_to('myaddress@mydomain.com', 'contact', 'encode=true') ?>
 395  >      => <a href="&#109;&#x61;... &#111;&#x6d;">&#x63;&#x74;... e&#115;&#x73;</a>
 396  >
 397  >Encoded e-mail messages are composed of characters transformed by a random decimal and hexadecimal entity encoder. This trick stops most of the address-harvesting spambots for now, but be aware that the harvesting techniques evolve rapidly.
 398  
 399  Routing Configuration
 400  ---------------------
 401  
 402  The routing system does two things:
 403  
 404    * It interprets the external URL of incoming requests and transforms it into an internal URI, to determine the module/action and the request parameters.
 405    * It formats the internal URIs used in links into external URLs (provided that you use the link helpers).
 406  
 407  The conversion is based on a set of routing rules . These rules are stored in a `routing.yml` configuration file located in the application `config/` directory. Listing 9-15 shows the default routing rules, bundled with every symfony project.
 408  
 409  Listing 9-15 - The Default Routing Rules, in `myapp/config/routing.yml`
 410  
 411      # default rules
 412      homepage:
 413        url:   /
 414        param: { module: default, action: index }
 415  
 416      default_symfony:
 417        url:   /symfony/:action/*
 418        param: { module: default }
 419  
 420      default_index:
 421        url:   /:module
 422        param: { action: index }
 423  
 424      default:
 425        url:   /:module/:action/*
 426  
 427  ### Rules and Patterns
 428  
 429  Routing rules are bijective associations between an external URL and an internal URI. A typical rule is made up of the following:
 430  
 431    * A unique label, which is there for legibility and speed, and can be used by the link helpers
 432    * A pattern to be matched (`url` key)
 433    * An array of request parameter values (`param` key)
 434  
 435  Patterns can contain wildcards (represented by an asterisk, *) and named wildcards (starting with a colon, :). A match to a named wildcard becomes a request parameter value. For instance, the `default` rule defined in Listing 9-15 will match any URL like `/foo/bar`, and set the `module` parameter to `foo` and the `action` parameter to `bar`. And in the `default_symfony` rule, `symfony` is a keyword and `action` is named wildcard parameter.
 436  
 437  The routing system parses the `routing.yml` file from the top to the bottom and stops at the first match. This is why you must add your own rules on top of the default ones. For instance, the URL `/foo/123` matches both of the rules defined in Listing 9-16, but symfony first tests `my_rule:`, and as that rule matches, it doesn't even test the `default:` one. The request is handled by the `mymodule/myaction` action with `bar` set to `123` (and not by the `foo/123` action).
 438  
 439  Listing 9-16 - Rules Are Parsed Top to Bottom
 440  
 441      my_rule:
 442        url:   /foo/:bar
 443        param: { module: mymodule, action: myaction }
 444  
 445      # default rules
 446      default:
 447        url:   /:module/:action/*
 448  
 449  >**NOTE**
 450  >When a new action is created, it does not imply that you must create a routing rule for it. If the default module/action pattern suits you, then forget about the `routing.yml` file. If, however, you want to customize the action's external URL, add a new rule above the default one.
 451  
 452  Listing 9-17 shows the process of changing the external URL format for an article/read action.
 453  
 454  Listing 9-17 - Changing the External URL Format for an `article/read` Action
 455  
 456      [php]
 457      <?php echo url_for('my article', 'article/read?id=123) ?>
 458       => /article/read/id/123       // Default formatting
 459  
 460      // To change it to /article/123, add a new rule at the beginning
 461      // of your routing.yml
 462      article_by_id:
 463        url:   /article/:id
 464        param: { module: article, action: read }
 465  
 466  The problem is that the `article_by_id` rule in Listing 9-17 breaks the default routing for all the other actions of the `article` module. In fact, a URL like `article/delete` will match this rule instead of the `default` one, and call the `read` action with `id` set to `delete` instead of the `delete` action. To get around this difficulty, you must add a pattern constraint so that the `article_by_id` rule matches only URLs where the `id` wildcard is an integer.
 467  
 468  ### Pattern Constraints
 469  
 470  When a URL can match more than one rule, you must refine the rules by adding constraints, or requirements, to the pattern. A requirement is a set of regular expressions that must be matched by the wildcards for the rule to match.
 471  
 472  For instance, to modify the `article_by_id` rule so that it matches only URLs where the `id` parameter is an integer, add a line to the rule, as shown in Listing 9-18.
 473  
 474  Listing 9-18 - Adding a Requirement to a Routing Rule
 475  
 476      article_by_id:
 477        url:   /article/:id
 478        param: { module: article, action: read }
 479        requirements: { id: \d+ }
 480  
 481  Now an `article/delete` URL can't match the `article_by_id` rule anymore, because the `'delete'` string doesn't satisfy the requirements. Therefore, the routing system will keep on looking for a match in the following rules and finally find the `default` rule.
 482  
 483  >**SIDEBAR**
 484  >Permalinks
 485  >
 486  >A good security guideline for routing is to hide primary keys and replace them with significant strings as much as possible. What if you wanted to give access to articles from their title rather than from their ID? It would make external URLs look like this:
 487  >
 488  >     http://www.example.com/article/Finance_in_France
 489  >
 490  >To that extent, you need to create a new `permalink` action, which will use a `slug` parameter instead of an `id` one, and add a new rule for it:
 491  >
 492  >     article_by_id:
 493  >       url:          /article/:id
 494  >       param:        { module: article, action: read }
 495  >       requirements: { id: \d+ }
 496  >
 497  >     article_by_slug:
 498  >       url:          /article/:slug
 499  >       param:        { module: article, action: permalink }
 500  >
 501  >The `permalink` action needs to determine the requested article from its title, so your model must provide an appropriate method.
 502  >
 503  >     [php]
 504  >     public function executePermalink()
 505  >     {
 506  >       $article = ArticlePeer::retrieveBySlug($this->getRequestParameter('slug');
 507  >       $this->forward404Unless($article);  // Display 404 if no article matches slug
 508  >       $this->article = $article;          // Pass the object to the template
 509  >     }
 510  >
 511  >You also need to replace the links to the `read` action in your templates with links to the `permalink` one, to enable correct formatting of internal URIs.
 512  >
 513  >     [php]
 514  >     // Replace
 515  >     <?php echo link_to('my article', 'article/read?id='.$article->getId()) ?>
 516  >
 517  >     // With
 518  >     <?php echo link_to('my article', 'article/permalink?slug='.$article->getSlug()) ?>
 519  >
 520  >Thanks to the `requirements` line, an external URL like `/article/Finance_in_France` matches the `article_by_slug` rule, even though the `article_by_id` rule appears first.
 521  >
 522  >Note that as articles will be retrieved by slug, you should add an index to the `slug` column in the `Article` model description to optimize database performance.
 523  
 524  ### Setting Default Values
 525  
 526  You can give named wildcards a default value to make a rule work, even if the parameter is not defined. Set default values in the `param:` array.
 527  
 528  For instance, the `article_by_id` rule doesn't match if the `id` parameter is not set. You can force it, as shown in Listing 9-19.
 529  
 530  Listing 9-19 - Setting a Default Value for a Wildcard
 531  
 532      article_by_id:
 533        url:          /article/:id
 534        param:        { module: article, action: read,
 535      id: 1
 536       }
 537  
 538  The default parameters don't need to be wildcards found in the pattern. In Listing 9-20, the `display` parameter takes the value `true`, even if it is not present in the URL.
 539  
 540  Listing 9-20 - Setting a Default Value for a Request Parameter
 541  
 542      article_by_id:
 543        url:          /article/:id
 544        param:        { module: article, action: read, id: 1, display: true }
 545  
 546  If you look carefully, you can see that `article` and `read` are also default values for `module` and `action` variables not found in the pattern.
 547  
 548  >**TIP**
 549  >You can define a default parameter for all the routing rules by defining the `sf_routing_default` configuration parameter. For instance, if you want all the rules to have a `theme` parameter set to `default` by default, add the line `sfConfig::set('sf_routing_defaults', array('theme' => 'default'));` to your application's `config.php`.
 550  
 551  ### Speeding Up Routing by Using the Rule Name
 552  
 553  The link helpers accept a  rule label instead of a module/action pair if the rule label is preceded by an at sign (@), as shown in Listing 9-21.
 554  
 555  Listing 9-21 - Using the Rule Label Instead of the Module/Action
 556  
 557      [php]
 558      <?php echo link_to('my article', 'article/read?id='.$article->getId()) ?>
 559  
 560      // can also be written as
 561      <?php echo link_to('my article', '@article_by_id?id='.$article->getId()) ?>
 562  
 563  There are pros and cons to this trick. The advantages are as follows:
 564  
 565    * The formatting of internal URIs is done much faster, since symfony doesn't have to browse all the rules to find the one that matches the link. In a page with a great number of routed hyperlinks, the boost will be noticeable if you use rule labels instead of module/action pairs.
 566    * Using the rule label helps to abstract the logic behind an action. If you decide to change an action name but keep the URL, a simple change in the `routing.yml` file will suffice. All of the `link_to()` calls will still work without further change.
 567    * The logic of the call is more apparent with a rule name. Even if your modules and actions have explicit names, it is often better to call `@display_article_by_slug` than `article/display`.
 568  
 569  On the other hand, a disadvantage is that adding new hyperlinks becomes less self-evident, since you always need to refer to the `routing.yml` file to find out which label is to be used for an action.
 570  
 571  The best choice depends on the project. In the long run, it's up to you.
 572  
 573  >**TIP**
 574  >During your tests (in the `dev` environment), if you want to check which rule was matched for a given request in your browser, develop the "logs and msgs" section of the web debug toolbar and look for a line specifying "matched route XXX." You will find more information about the web debug mode in Chapter 16.
 575  
 576  ### Adding an .html Extension
 577  
 578  Compare these two URLs:
 579  
 580      http://myapp.example.com/article/Finance_in_France
 581      http://myapp.example.com/article/Finance_in_France.html
 582  
 583  Even if it is the same page, users and (robots) may see it differently because of the URL. The second URL evokes a deep and well-organized web directory of static pages, which is exactly the kind of websites that search engines know how to index.
 584  
 585  To add a suffix to every external URL generated by the routing system, change the `suffix` value in the application `settings.yml`, as shown in Listing 9-22.
 586  
 587  Listing 9-22 - Setting a Suffix for All URLs, in `myapp/config/settings.yml`
 588  
 589      prod:
 590        .settings
 591          suffix:         .html
 592  
 593  The default suffix is set to a period (`.`), which means that the routing system doesn't add a suffix unless you specify it.
 594  
 595  It is sometimes necessary to specify a suffix for a unique routing rule. In that case, write the suffix directly in the related `url:` line of the `routing.yml` file, as shown in Listing 9-23. Then the global suffix will be ignored.
 596  
 597  Listing 9-23 - Setting a Suffix for One URL, in `myapp/config/routing.yml`
 598  
 599      article_list:
 600        url:          /latest_articles
 601        param:        { module: article, action: list }
 602  
 603      article_list_feed:
 604        url:          /latest_articles.rss
 605        param:        { module: article, action: list, type: feed }
 606  
 607  ### Creating Rules Without routing.yml
 608  
 609  As is true of most of the configuration files, the `routing.yml` is a solution to define routing rules, but not the only one. You can define rules in PHP, either in the application `config.php` file or in the front controller script, but before the call to `dispatch()`, because this method determines the action to execute according to the present routing rules. Defining rules in PHP authorizes you to create dynamic rules, depending on configuration or other parameters.
 610  
 611  The object that handles the routing rules is the `sfRouting` singleton. It is available from every part of the code by requiring `sfRouting::getInstance()`. Its `prependRoute()` method adds a new rule on top of the existing ones defined in `routing.yml`. It expects four parameters, which are the same as the parameters needed to define a rule: a route label, a pattern, an associative array of default values, and another associative array for requirements. For instance, the routing.yml rule definition shown in Listing 9-18 is equivalent to the PHP code shown in Listing 9-24.
 612  
 613  Listing 9-24 - Defining a Rule in PHP
 614  
 615      [php]
 616      sfRouting::getInstance()->prependRoute(
 617        'article_by_id',                                  // Route name
 618        '/article/:id',                                   // Route pattern
 619        array('module' => 'article', 'action' => 'read'), // Default values
 620        array('id' => '\d+'),                             // Requirements
 621      );
 622  
 623  The sfRouting singleton has other useful methods for handling routes by hand: clearRoutes(), h`asRoutes()`, `getRoutesByName()`, and so on. Refer to the API documentation ([http://www.symfony-project.com/api/symfony.html](http://www.symfony-project.com/api/symfony.html)) to learn more.
 624  
 625  >**TIP**
 626  >Once you start to fully understand the concepts presented in this book, you can increase your understanding of the framework by browsing the online API documentation or, even better, the symfony source. Not all the tweaks and parameters of symfony can be described in this book. The online documentation, however, is limitless.
 627  
 628  Dealing with Routes in Actions
 629  ------------------------------
 630  
 631  If you need to retrieve information about the current route--for instance, to prepare a future "back to page xxx" link--you should use the methods of the sfRouting object. The URIs returned by the `getCurrentInternalUri()` method can be used in a call to a `link_to()` helper, as shown in Listing 9-25.
 632  
 633  Listing 9-25 - Using `sfRouting` to Get Information About the Current Route
 634  
 635      [php]
 636      // If you require a URL like
 637      http://myapp.example.com/article/21
 638  
 639      // Use the following in article/read action
 640      $uri = sfRouting::getInstance()->getCurrentInternalUri();
 641       => article/read?id=21
 642  
 643      $uri = sfRouting::getInstance()->getCurrentInternalUri(true);
 644       => @article_by_id?id=21
 645  
 646      $rule = sfRouting::getInstance()->getCurrentRouteName();
 647       => article_by_id
 648  
 649      // If you just need the current module/action names,
 650      // remember that they are actual request parameters
 651      $module = $this->getRequestParameter('module');
 652      $action = $this->getRequestParameter('action');
 653  
 654  If you need to transform an internal URI into an external URL in an action--just as `url_for()` does in a template--use the `genUrl()` method of the sfController object, as shown in Listing 9-26.
 655  
 656  Listing 9-26 - Using `sfController` to Transform an Internal URI
 657  
 658      [php]
 659      $uri = 'article/read?id=21';
 660  
 661      $url = $this->getController()->genUrl($uri);
 662       => /article/21
 663  
 664      $url = $this->getController()->genUrl($uri, true);
 665      => http://myapp.example.com/article/21
 666  
 667  Summary
 668  -------
 669  
 670  Routing is a two-way mechanism designed to allow formatting of external URLs so that they are more user-friendly. URL rewriting is required to allow the omission of the front controller name in the URLs of one of the applications of each project. You must use link helpers each time you need to output a URL in a template if you want the routing system to work both ways. The `routing.yml` file configures the rules of the routing system and uses an order of precedence and rule requirements. The `settings.yml` file contains additional settings concerning the presence of the front controller name and a possible suffix in external URLs.


Généré le : Fri Mar 16 22:42:14 2007 par Balluche grâce à PHPXref 0.7