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** >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_context`, `$sf_request`, `$sf_params`, and `$sf_user` objects. They contain data related to the current context, request, request parameters, and session. You will soon learn how to use them efficiently. Gathering Information from the User with Forms ---------------------------------------------- Forms are a good way to get information from the user. Writing form and form elements in HTML can sometimes be cumbersome, especially when you want to be XHTML-compliant. You could include form elements in symfony templates the usual way, as shown in Listing 4-8, but symfony provides helpers that make this task easier. Listing 4-8 - Templates Can Include Usual HTML Code [php]Hello, world!
= 18): ?>Or should I say good evening? It is already .
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. Using symfony helpers, you can have the same result as in Listing 4-8 with the code shown in Listing 4-9. Listing 4-9 - It Is Faster and Easier to Use Helpers Than to Use HTML Tags [php]Hello, world!
= 18): ?>Or should I say good evening? It is already .
>**SIDEBAR** >Helpers are here to help you > >If, in the example in Listing 4-9, you think the helper version is not really faster to write than the HTML one, consider this one: > > [php] > $card_list = array( > 'VISA' => 'Visa', > 'MAST' => 'MasterCard', > 'AMEX' => 'American Express', > 'DISC' => 'Discover'); > echo select_tag('cc_type', options_for_select($card_list, 'AMEX')); > ?> > >This outputs the following HTML: > > [php] > > >The benefit of helpers in templates is raw speed of coding, clarity of code, and concision. The only price to pay is the time to learn them, which will end when you finish this book, and the time to write , for which you should already have a shortcut in your favorite text editor. So you could not use the symfony helpers in templates and write HTML the way you always did, but this would be a great loss and much less fun. Note that the use of the short opening tags (`=`, equivalent to ` 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. Listing 4-11 demonstrates the use of the hyperlink helper. Listing 4-11 - The `link_to()` Helper [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. 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 the form 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 `getRequestParameter()` method of the `sfActions` object. Listing 4-13 shows how, in `anotherAction`, you retrieve the value of the `name` parameter. Listing 4-13 - Getting Data from the Request Parameter in the Action [php] name = $this->getRequestParameter('name'); } } 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 getRequestParameter() in the action. If `executeAnotherAction()` were empty, Listing 4-14 shows how the `anotherActionSuccess.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 `getRequestParameter()` 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.