Chapter 4 - The Basics Of Page Creation
=======================================
Curiously, the first tutorial that programmers follow when learning a new language or a framework is the one that displays "Hello, world!" on the screen. It is strange to think of the computer as something that can greet the whole world, since every attempt in the artificial intelligence field has so far resulted in poor conversational abilities. But symfony isn't dumber than any other program, and the proof is, you can create a page that says "Hello, ` Hello, world! Hello, world!
Hello, world!
>**TIP** >A good rule of thumb to check if the template syntax is readable enough is that the file should not contain HTML code echoed by PHP or curly brackets. And most of the time, when opening a `` in the same line. ### Passing Information from the Action to the Template The job of the action is to do all the complicated calculation, data retrieval, and tests, and to set variables for the template to be echoed or tested. Symfony makes the attributes of the action class (accessed via `$this->variableName` in the action) directly accessible to the template in the global namespace (via `$variableName`). Listings 4-6 and 4-7 show how to pass information from the action to the template. Listing 4-6 - Setting an Action Attribute in the Action to Make It Available to the Template [php] hour = $today['hours']; } } Listing 4-7 - The Template Has Direct Access to the Action Attributes [php]Hello, world!
= 18): ?>Or should I say good evening? It is already .
Note that the use of the short opening tags (`=`, equivalent to `**NOTE** >The template already has access to a few pieces of data without the need of any variable setup in the action. Every template can call methods of the `$sf_request`, `$sf_params`, `$sf_response`, and `$sf_user` objects. They contain data related to the current request, request parameters, response, and session. You will soon learn how to use them efficiently. Linking to Another Action ------------------------- You already know that there is a total decoupling between an action name and the URL used to call it. So if you create a link to `update` in a template as in Listing 4-10, it will only work with the default routing. If you later decide to change the way the URLs look, then you will need to review all templates to change the hyperlinks. Listing 4-10 - Hyperlinks, the Classic Way [php] I never say my name To avoid this hassle, you should always use the `link_to()` helper to create hyperlinks to your application's actions. And if you only want to generate the URL part, the `url_for()` is the helper you're looking for. A helper is a PHP function defined by symfony that is meant to be used within templates. It outputs some HTML code and is faster to use than writing the actual HTML code by yourself. Listing 4-11 demonstrates the use of the hyperlink helpers. Listing 4-11 - The `link_to()`, and `url_for()` Helpers [php]Hello, world!
= 18): ?>Or should I say good evening? It is already .
The resulting HTML will be the same as previously, except that when you change your routing rules, all the templates will behave correctly and reformat the URLs accordingly. Form manipulation deserves a whole chapter of its own, since symfony provides many tools to make it even easier. You will learn more about these helpers in Chapter 10. The `link_to()` helper, like many other helpers, accepts another argument for special options and additional tag attributes. Listing 4-12 shows an example of an option argument and the resulting HTML. The option argument is either an associative array or a simple string showing `key=value` couples separated by blanks. Listing 4-12 - Most Helpers Accept an Option Argument [php] // Option argument as an associative array 'special_link', 'confirm' => 'Are you sure?', 'absolute' => true )) ?> // Option argument as a string // Both calls output the same => I never say my name Whenever you use a symfony helper that outputs an HTML tag, you can insert additional tag attributes (like the `class` attribute in the example in Listing 4-12) in the option argument. You can even write these attributes in the "quick-and-dirty" HTML 4.0 way (without double quotes), and symfony will output them in nicely formatted XHTML. That's another reason why helpers are faster to write than HTML. >**NOTE** >Because it requires an additional parsing and transformation, the string syntax is a little slower than the array syntax. Like all symfony helpers, the link helpers are numerous and have many options. Chapter 9 will describe them in detail. Getting Information from the Request ------------------------------------ Whether the user sends information via a form (usually in a POST request) or via the URL (GET request), you can retrieve the related data from the action with the `getParameter()` method of the `sfRequest` object. Listing 4-13 shows how, in `update`, you retrieve the value of the `name` parameter. Listing 4-13 - Getting Data from the Request Parameter in the Action [php] name = $request->getParameter('name'); } } As a convenience, all `executeXxx()` methods take the current `sfRequest` object as its first argument. If the data manipulation is simple, you don't even need to use the action to retrieve the request parameters. The template has access to an object called `$sf_params`, which offers a `get`() method to retrieve the request parameters, just like the `getParameter()` in the action. If `executeUpdate()` were empty, Listing 4-14 shows how the `updateSuccess.php` template would retrieve the same `name` parameter. Listing 4-14 - Getting Data from the Request Parameter Directly in the Template [php]Hello, get('name') ?>!
>**NOTE** >Why not use the `$_POST`, `$_GET`, or `$_REQUEST` variables instead? Because then your URLs will be formatted differently (as in `http://localhost/articles/europe/france/finance.html`, without `?` nor `=`), the usual PHP variables won't work anymore, and only the routing system will be able to retrieve the request parameters. And you may want to add input filtering to prevent malicious code injection, which is only possible if you keep all request parameters in one clean parameter holder. The `$sf_params` object is more powerful than just giving a getter equivalent to an array. For instance, if you only want to test the existence of a request parameter, you can simply use the `$sf_params->has()` method instead of testing the actual value with `get()`, as in Listing 4-15. Listing 4-15 - Testing the Existence of a Request Parameter in the Template [php] has('name')): ?>Hello, get('name') ?>!
Hello, John Doe!
You may have already guessed that this can be written in a single line. As with most getter methods in symfony, both the `$request->getParameter()` method in the action and the `$sf_params->get()` method in the template (which, as a matter of fact, calls the same method on the same object) accept a second argument: the default value to be used if the request parameter is not present. [php]Hello, get('name', 'John Doe') ?>!
Summary ------- In symfony, pages are composed of an action (a method in the `actions/actions.class.php` file prefixed with `execute`) and a template (a file in the `templates/` directory, usually ending with `Success.php`). They are grouped in modules, according to their function in the application. Writing templates is facilitated by helpers, which are functions provided by symfony that return HTML code. And you need to think of the URL as a part of the response, which can be formatted as needed, so you should refrain from using any direct reference to the URL in action naming or request parameter retrieval. Once you know these basic principles, you can already write a whole web application with symfony. But it would take you way too long, since almost every task you will have to achieve during the course of the application development is facilitated one way or another by some symfony feature... which is why the book doesn't stop now.