09-Links-and-the-Routing-System.txt 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. Chapter 9 - Links And The Routing System
  2. ========================================
  3. 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:
  4. * What the routing system is and how it works
  5. * How to use link helpers in templates to enable routing of outgoing URLs
  6. * How to configure the routing rules to change the appearance of URLs
  7. You will also find a few tricks for mastering routing performance and adding finishing touches.
  8. What Is Routing?
  9. ----------------
  10. 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.
  11. ### URLs As Server Instructions
  12. 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:
  13. http://www.example.com/web/controller/article.php?id=123456&format_code=6532
  14. 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:
  15. * 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.
  16. * 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.
  17. Figure 9-1 - URLs appear in many places, such as in search results
  18. ![URLs appear in many places, such as in search results](/images/book/F0901.png "URLs appear in many places, such as in search results")
  19. * 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.
  20. 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:
  21. http://www.example.com/web/gallery/album.php?name=my%20holidays
  22. http://www.example.com/web/weblog/public/post/list.php
  23. http://www.example.com/web/general/content/page.php?name=about%20us
  24. In this case, developers would need to match the URL structure with the file structure, resulting in a maintenance nightmare when either structure changed.
  25. ### URLs As Part of the Interface
  26. 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.
  27. 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:
  28. http://www.example.com/articles/finance/2006/activity-breakdown.html
  29. The benefits are immense:
  30. * 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.
  31. Figure 9-2 - URLs can convey additional information about a page, like the publication date
  32. ![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")
  33. * 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.
  34. * 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.
  35. // List of results: add a new tag to narrow the list of results
  36. http://del.icio.us/tag/symfony+ajax
  37. // User profile page: change the name to get another user profile
  38. http://www.askeet.com/user/francois
  39. * 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.
  40. * 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.
  41. * 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.
  42. * 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.
  43. 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.
  44. >**NOTE**
  45. >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))`.
  46. ### How It Works
  47. 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.
  48. Listing 9-1 - External URL and Internal URI
  49. // Internal URI syntax
  50. <module>/<action>[?param1=value1][&param2=value2][&param3=value3]...
  51. // Example internal URI, which never appears to the end user
  52. article/permalink?year=2006&subject=finance&title=activity-breakdown
  53. // Example external URL, which appears to the end user
  54. http://www.example.com/articles/finance/2006/activity-breakdown.html
  55. 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.
  56. Listing 9-2 - A Sample Routing Rule
  57. article_by_title:
  58. url: articles/:subject/:year/:title.html
  59. param: { module: article, action: permalink }
  60. 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.
  61. Listing 9-3 - The Routing System Interprets Incoming Request URLs
  62. // The user types (or clicks on) this external URL
  63. http://www.example.com/articles/finance/2006/activity-breakdown.html
  64. // The front controller sees that it matches the article_by_title rule
  65. // The routing system creates the following request parameters
  66. 'module' => 'article'
  67. 'action' => 'permalink'
  68. 'subject' => 'finance'
  69. 'year' => '2006'
  70. 'title' => 'activity-breakdown'
  71. >**TIP**
  72. >The `.html` extension of the external URL is a simple decoration and is ignored by the routing system. Its sole interest is to make dynamic pages look like static ones. You will see how to activate this extension in the "Routing Configuration" section later in this chapter.
  73. 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.
  74. 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.
  75. Listing 9-4 - The Routing System Formats Outgoing URLs in Templates
  76. [php]
  77. // The url_for() helper transforms an internal URI into an external URL
  78. <a href="<?php echo url_for('article/permalink?subject=finance&year=2006&title=activity-breakdown') ?>">click here</a>
  79. // The helper sees that the URI matches the article_by_title rule
  80. // The routing system creates an external URL out of it
  81. => <a href="http://www.example.com/articles/finance/2006/activity-breakdown.html">click here</a>
  82. // The link_to() helper directly outputs a hyperlink
  83. // and avoids mixing PHP with HTML
  84. <?php echo link_to(
  85. 'click here',
  86. 'article/permalink?subject=finance&year=2006&title=activity-breakdown'
  87. ) ?>
  88. // Internally, link_to() will make a call to url_for() so the result is the same
  89. => <a href="http://www.example.com/articles/finance/2006/activity-breakdown.html">click here</a>
  90. So routing is a two-way mechanism, and it works only if you use the `link_to()` helper to format all your links.
  91. URL Rewriting
  92. -------------
  93. 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 `frontend_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.
  94. 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.
  95. Listing 9-5 - Showing the Front Controller Name in URLs, in `apps/frontend/config/settings.yml`
  96. prod:
  97. .settings
  98. no_script_name: off
  99. Now, the generated URLs will look like this:
  100. http://www.example.com/index.php/articles/finance/2006/activity-breakdown.html
  101. 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.
  102. http://www.example.com/frontend_dev.php/articles/finance/2006/activity-breakdown.html
  103. 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.
  104. http://www.example.com/articles/finance/2006/activity-breakdown.html
  105. 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.
  106. 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.
  107. Listing 9-6 - Default Rewriting Rules for Apache, in `myproject/web/.htaccess`
  108. <IfModule mod_rewrite.c>
  109. RewriteEngine On
  110. # we skip all files with .something
  111. RewriteCond %{REQUEST_URI} \..+$
  112. RewriteCond %{REQUEST_URI} !\.html$
  113. RewriteRule .* - [L]
  114. # we check if the .html version is here (caching)
  115. RewriteRule ^$ index.html [QSA]
  116. RewriteRule ^([^.]+)$ $1.html [QSA]
  117. RewriteCond %{REQUEST_FILENAME} !-f
  118. # no, so we redirect to our front web controller
  119. RewriteRule ^(.*)$ index.php [QSA,L]
  120. </IfModule>
  121. 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`.
  122. 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:
  123. index.php // frontend in prod
  124. frontend_dev.php // frontend in dev
  125. backend.php // backend in prod
  126. backend_dev.php // backend in dev
  127. 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.
  128. >**TIP**
  129. >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 path to the `ProjectConfiguration` file accordingly, and create the `.htaccess` URL rewriting configuration that you need for each application.
  130. Link Helpers
  131. ------------
  132. 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.
  133. ### Hyperlinks, Buttons, and Forms
  134. 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.
  135. Listing 9-7 - Link Helpers for `<a>`, `<input>`, and `<form>` Tags
  136. [php]
  137. // Hyperlink on a string
  138. <?php echo link_to('my article', 'article/read?title=Finance_in_France') ?>
  139. => <a href="/routed/url/to/Finance_in_France">my article</a>
  140. // Hyperlink on an image
  141. <?php echo link_to(image_tag('read.gif'), 'article/read?title=Finance_in_France') ?>
  142. => <a href="/routed/url/to/Finance_in_France"><img src="/images/read.gif" /></a>
  143. // Button tag
  144. <?php echo button_to('my article', 'article/read?title=Finance_in_France') ?>
  145. => <input value="my article" type="button"onclick="document.location.href='/routed/url/to/Finance_in_France';" />
  146. // Form tag
  147. <?php echo form_tag('article/read?title=Finance_in_France') ?>
  148. => <form method="post" action="/routed/url/to/Finance_in_France" />
  149. 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.
  150. Listing 9-8 - URLs Accepted by Link Helpers
  151. [php]
  152. // Internal URI
  153. <?php echo link_to('my article', 'article/read?title=Finance_in_France') ?>
  154. => <a href="/routed/url/to/Finance_in_France">my article</a>
  155. // Internal URI with dynamic parameters
  156. <?php echo link_to('my article', 'article/read?title='.$article->getTitle()) ?>
  157. // Internal URI with anchors
  158. <?php echo link_to('my article', 'article/read?title=Finance_in_France#foo') ?>
  159. => <a href="/routed/url/to/Finance_in_France#foo">my article</a>
  160. // Absolute URL
  161. <?php echo link_to('my article', 'http://www.example.com/foobar.html') ?>
  162. => <a href="http://www.example.com/foobar.html">my article</a>
  163. ### Link Helper Options
  164. 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.
  165. Listing 9-9 - Link Helpers Accept Additional Options
  166. [php]
  167. // Additional options as an associative array
  168. <?php echo link_to('my article', 'article/read?title=Finance_in_France', array(
  169. 'class' => 'foobar',
  170. 'target' => '_blank'
  171. )) ?>
  172. // Additional options as a string (same result)
  173. <?php echo link_to('my article', 'article/read?title=Finance_in_France','class=foobar target=_blank') ?>
  174. => <a href="/routed/url/to/Finance_in_France" class="foobar" target="_blank">my article</a>
  175. 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.
  176. Listing 9-10 - `'confirm'` and `'popup'` Options for Link Helpers
  177. [php]
  178. <?php echo link_to('delete item', 'item/delete?id=123', 'confirm=Are you sure?') ?>
  179. => <a onclick="return confirm('Are you sure?');"
  180. href="/routed/url/to/delete/123.html">delete item</a>
  181. <?php echo link_to('add to cart', 'shoppingCart/add?id=100', 'popup=true') ?>
  182. => <a onclick="window.open(this.href);return false;"
  183. href="/fo_dev.php/shoppingCart/add/id/100.html">add to cart</a>
  184. <?php echo link_to('add to cart', 'shoppingCart/add?id=100', array(
  185. 'popup' => array('popupWindow', 'width=310,height=400,left=320,top=0')
  186. )) ?>
  187. => <a onclick="window.open(this.href,'popupWindow','width=310,height=400,left=320,top=0');return false;"
  188. href="/fo_dev.php/shoppingCart/add/id/100.html">add to cart</a>
  189. These options can be combined.
  190. ### Fake GET and POST Options
  191. Sometimes web developers use GET requests to actually do a POST. For instance, consider the following URL:
  192. http://www.example.com/index.php/shopping_cart/add/id/100
  193. 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.
  194. 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.
  195. Listing 9-11 - Making a Link Call a POST Request
  196. [php]
  197. <?php echo link_to('go to shopping cart', 'shoppingCart/add?id=100', 'post=true') ?>
  198. => <a onclick="f = document.createElement('form'); document.body.appendChild(f);
  199. f.method = 'POST'; f.action = this.href; f.submit();return false;"
  200. href="/shoppingCart/add/id/100.html">go to shopping cart</a>
  201. 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:
  202. [php]
  203. $this->forward404Unless($this->getRequest()->isMethod('post'));
  204. Just make sure you don't use this option on links located in forms, since it generates its own `<form>` tag.
  205. It is a good habit to tag as POST the links that actually post data.
  206. ### Forcing Request Parameters As GET Variables
  207. 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.
  208. Listing 9-12 - Default Routing Rule
  209. [php]
  210. <?php echo link_to('my article', 'article/read?title=Finance_in_France') ?>
  211. => <a href="/article/read/title/Finance_in_France">my article</a>
  212. 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.
  213. As this would conflict also with an anchor in the URL, you have to put it into the `anchor` option instead of prepending it to the internal URI. All the link helpers accept these options, as demonstrated in Listing 9-13.
  214. Listing 9-13 - Forcing GET Variables with the `query_string` Option
  215. [php]
  216. <?php echo link_to('my article', 'article/read', array(
  217. 'query_string' => 'title=Finance_in_France',
  218. 'anchor' => 'foo'
  219. )) ?>
  220. => <a href="/article/read?title=Finance_in_France#foo">my article</a>
  221. 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.
  222. >**SIDEBAR**
  223. >Asset helpers
  224. >
  225. >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.
  226. >
  227. >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.
  228. >
  229. > [php]
  230. > <?php echo image_tag('test') ?>
  231. > <?php echo image_tag('test.gif') ?>
  232. > <?php echo image_tag('/my_images/test.gif') ?>
  233. > => <img href="/images/test.png" alt="Test" />
  234. > <img href="/images/test.gif" alt="Test" />
  235. > <img href="/my_images/test.gif" alt="Test" />
  236. >
  237. >To fix the size of an image, use the `size` attribute. It expects a width and a height in pixels, separated by an `x`.
  238. >
  239. > [php]
  240. > <?php echo image_tag('test', 'size=100x20')) ?>
  241. > => <img href="/images/test.png" alt="Test" width="100" height="20"/>
  242. >
  243. >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.
  244. ### Using Absolute Paths
  245. 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.
  246. Listing 9-14 - Getting Absolute URLs Instead of Relative URLs
  247. [php]
  248. <?php echo url_for('article/read?title=Finance_in_France') ?>
  249. => '/routed/url/to/Finance_in_France'
  250. <?php echo url_for('article/read?title=Finance_in_France', true) ?>
  251. => 'http://www.example.com/routed/url/to/Finance_in_France'
  252. <?php echo link_to('finance', 'article/read?title=Finance_in_France') ?>
  253. => <a href="/routed/url/to/Finance_in_France">finance</a>
  254. <?php echo link_to('finance', 'article/read?title=Finance_in_France','absolute=true') ?>
  255. => <a href=" http://www.example.com/routed/url/to/Finance_in_France">finance</a>
  256. // The same goes for the asset helpers
  257. <?php echo image_tag('test', 'absolute=true') ?>
  258. <?php echo javascript_include_tag('myscript', 'absolute=true') ?>
  259. >**SIDEBAR**
  260. >The Mail helper
  261. >
  262. >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.
  263. >
  264. >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.
  265. >
  266. > [php]
  267. > <?php echo mail_to('myaddress@mydomain.com', 'contact') ?>
  268. > => <a href="mailto:myaddress@mydomain.com'>contact</a>
  269. > <?php echo mail_to('myaddress@mydomain.com', 'contact', 'encode=true') ?>
  270. > => <a href="&#109;&#x61;... &#111;&#x6d;">&#x63;&#x74;... e&#115;&#x73;</a>
  271. >
  272. >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.
  273. Routing Configuration
  274. ---------------------
  275. The routing system does two things:
  276. * It interprets the external URL of incoming requests and transforms it into an internal URI, to determine the module/action and the request parameters.
  277. * It formats the internal URIs used in links into external URLs (provided that you use the link helpers).
  278. 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.
  279. Listing 9-15 - The Default Routing Rules, in `frontend/config/routing.yml`
  280. # default rules
  281. homepage:
  282. url: /
  283. param: { module: default, action: index }
  284. default_symfony:
  285. url: /symfony/:action/*
  286. param: { module: default }
  287. default_index:
  288. url: /:module
  289. param: { action: index }
  290. default:
  291. url: /:module/:action/*
  292. ### Rules and Patterns
  293. Routing rules are bijective associations between an external URL and an internal URI. A typical rule is made up of the following:
  294. * A unique label, which is there for legibility and speed, and can be used by the link helpers
  295. * A pattern to be matched (`url` key)
  296. * An array of request parameter values (`param` key)
  297. 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.
  298. >**NOTE**
  299. >**New in symfony 1.1** named wildcards can be separated by a slash or a dot, so you can write a pattern like:
  300. >
  301. > my_rule:
  302. > url: /foo/:bar.:format
  303. > param: { module: mymodule, action: myaction }
  304. >
  305. >That way, an external URL like 'foo/12.xml' will match `my_rule` and execute `mymodule/myaction` with two parameters: `$bar=12` and `$format=xml`.
  306. >You can add more separators by changing the `segment_separators` parameters value in the `sfPatternRouting` factory configuration (see chapter 19).
  307. 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).
  308. Listing 9-16 - Rules Are Parsed Top to Bottom
  309. my_rule:
  310. url: /foo/:bar
  311. param: { module: mymodule, action: myaction }
  312. # default rules
  313. default:
  314. url: /:module/:action/*
  315. >**NOTE**
  316. >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.
  317. Listing 9-17 shows the process of changing the external URL format for an article/read action.
  318. Listing 9-17 - Changing the External URL Format for an `article/read` Action
  319. [php]
  320. <?php echo url_for('article/read?id=123') ?>
  321. => /article/read/id/123 // Default formatting
  322. // To change it to /article/123, add a new rule at the beginning
  323. // of your routing.yml
  324. article_by_id:
  325. url: /article/:id
  326. param: { module: article, action: read }
  327. 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.
  328. ### Pattern Constraints
  329. 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.
  330. 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.
  331. Listing 9-18 - Adding a Requirement to a Routing Rule
  332. article_by_id:
  333. url: /article/:id
  334. param: { module: article, action: read }
  335. requirements: { id: \d+ }
  336. 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.
  337. >**SIDEBAR**
  338. >Permalinks
  339. >
  340. >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:
  341. >
  342. > http://www.example.com/article/Finance_in_France
  343. >
  344. >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:
  345. >
  346. > article_by_id:
  347. > url: /article/:id
  348. > param: { module: article, action: read }
  349. > requirements: { id: \d+ }
  350. >
  351. > article_by_slug:
  352. > url: /article/:slug
  353. > param: { module: article, action: permalink }
  354. >
  355. >The `permalink` action needs to determine the requested article from its title, so your model must provide an appropriate method.
  356. >
  357. > [php]
  358. > public function executePermalink($request)
  359. > {
  360. > $article = ArticlePeer::retrieveBySlug($request->getParameter('slug');
  361. > $this->forward404Unless($article); // Display 404 if no article matches slug
  362. > $this->article = $article; // Pass the object to the template
  363. > }
  364. >
  365. >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.
  366. >
  367. > [php]
  368. > // Replace
  369. > <?php echo link_to('my article', 'article/read?id='.$article->getId()) ?>
  370. >
  371. > // With
  372. > <?php echo link_to('my article', 'article/permalink?slug='.$article->getSlug()) ?>
  373. >
  374. >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.
  375. >
  376. >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.
  377. ### Setting Default Values
  378. 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.
  379. 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.
  380. Listing 9-19 - Setting a Default Value for a Wildcard
  381. article_by_id:
  382. url: /article/:id
  383. param: { module: article, action: read, id: 1 }
  384. 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.
  385. Listing 9-20 - Setting a Default Value for a Request Parameter
  386. article_by_id:
  387. url: /article/:id
  388. param: { module: article, action: read, id: 1, display: true }
  389. 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.
  390. >**TIP**
  391. >You can define a default parameter for all the routing rules by calling the `sfRouting::setDefaultParameter()` method. For instance, if you want all the rules to have a `theme` parameter set to `default` by default, add `$this->context->getRouting()->setDefaultParameter('theme', 'default');` to one of your global filters.
  392. ### Speeding Up Routing by Using the Rule Name
  393. 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.
  394. Listing 9-21 - Using the Rule Label Instead of the Module/Action
  395. [php]
  396. <?php echo link_to('my article', 'article/read?id='.$article->getId()) ?>
  397. // can also be written as
  398. <?php echo link_to('my article', '@article_by_id?id='.$article->getId()) ?>
  399. There are pros and cons to this trick. The advantages are as follows:
  400. * The formatting of internal URIs is done 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.
  401. * 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.
  402. * 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`.
  403. 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.
  404. The best choice depends on the project. In the long run, it's up to you.
  405. >**TIP**
  406. >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.
  407. >**NOTE**
  408. >**New in symfony 1.1** Routing operations are much faster in production mode, where conversions between external URLs and internal URIs are cached.
  409. ### Adding an .html Extension
  410. Compare these two URLs:
  411. http://myapp.example.com/article/Finance_in_France
  412. http://myapp.example.com/article/Finance_in_France.html
  413. 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.
  414. To add a suffix to every external URL generated by the routing system, change the `suffix` value in the application `factories.yml`, as shown in Listing 9-22.
  415. Listing 9-22 - Setting a Suffix for All URLs, in `frontend/config/factories.yml`
  416. prod:
  417. routing:
  418. param:
  419. suffix: .html
  420. The default suffix is set to a period (`.`), which means that the routing system doesn't add a suffix unless you specify it.
  421. 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.
  422. Listing 9-23 - Setting a Suffix for One URL, in `frontend/config/routing.yml`
  423. article_list:
  424. url: /latest_articles
  425. param: { module: article, action: list }
  426. article_list_feed:
  427. url: /latest_articles.rss
  428. param: { module: article, action: list, type: feed }
  429. ### Creating Rules Without routing.yml
  430. 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.
  431. The object that handles the routing rules is the `sfPatternRouting` factory. It is available from every part of the code by requiring `sfContext::getInstance()->getRouting()`. 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.
  432. >**NOTE**
  433. >**New in symfony 1.1**: The routing class is configurable in the `factories.yml` configuration file (to change the default routing class, see chapter 17). This chapter talks about the `sfPatternRouting` class, which is the routing class configured by default.
  434. Listing 9-24 - Defining a Rule in PHP
  435. [php]
  436. sfContext::getInstance()->getRouting()->prependRoute(
  437. 'article_by_id', // Route name
  438. '/article/:id', // Route pattern
  439. array('module' => 'article', 'action' => 'read'), // Default values
  440. array('id' => '\d+'), // Requirements
  441. );
  442. The `sfPatternRouting` class has other useful methods for handling routes by hand: `clearRoutes()`, `hasRoutes()` and so on. Refer to the API documentation ([http://www.symfony-project.org/api/1_1/](http://www.symfony-project.org/api/1_1/)) to learn more.
  443. >**TIP**
  444. >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.
  445. Dealing with Routes in Actions
  446. ------------------------------
  447. 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 `sfPatternRouting` 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.
  448. Listing 9-25 - Using `sfRouting` to Get Information About the Current Route
  449. [php]
  450. // If you require a URL like
  451. http://myapp.example.com/article/21
  452. $routing = sfContext::getInstance()->getRouting();
  453. // Use the following in article/read action
  454. $uri = $routing->getCurrentInternalUri();
  455. => article/read?id=21
  456. $uri = $routing->getCurrentInternalUri(true);
  457. => @article_by_id?id=21
  458. $rule = $routing->getCurrentRouteName();
  459. => article_by_id
  460. // If you just need the current module/action names,
  461. // remember that they are actual request parameters
  462. $module = $request->getParameter('module');
  463. $action = $request->getParameter('action');
  464. 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.
  465. Listing 9-26 - Using `sfController` to Transform an Internal URI
  466. [php]
  467. $uri = 'article/read?id=21';
  468. $url = $this->getController()->genUrl($uri);
  469. => /article/21
  470. $url = $this->getController()->genUrl($uri, true);
  471. => http://myapp.example.com/article/21
  472. Summary
  473. -------
  474. 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.