Basic creation of the page

Source: Internet
Author: User
Tags php template
In this chapter we will learn how to create a module, which is a structured element of the Organization page. At the same time we will learn how to create a page divided into an action and a template, the reason is divided into action and template, is because of the MVC pattern. Links and recognitions are basic page interactions, and we'll learn how to insert these elements into a template and process them in action.

Create a module framework

As we know in Chapter 2nd, Symfony organizes pages into modules. Before creating a page, we need to create a module and initialize it as an empty shell of a file structure that symfony can recognize.

Symfony the creation of the command line Automation processing module. We only need to invoke the Init-module task and use the program name and module name as parameters. In the previous chapter, we created a MyApp program. To add a MyModule module to this program, we can enter the following command:

> CD ~/myproject
> Symfony init-module MyApp mymodule

>> dir+ ~/myproject/apps/myapp/modules/mymodule
>> dir+ ~/myproject/apps/myapp/modules/mymodule/actions
>> file+ ~/myproject/apps/myapp/modules/mymodule/actions/actions.class.php
>> dir+ ~/myproject/apps/myapp/modules/mymodule/config
>> dir+ ~/myproject/apps/myapp/modules/mymodule/lib
>> dir+ ~/myproject/apps/myapp/modules/mymodule/templates
>> file+ ~/myproject/apps/myapp/modules/mymodule/templates/indexsuccess.php
>> dir+ ~/myproject/apps/myapp/modules/mymodule/validate
>> file+ ~/myproject/test/functional/myapp/mymoduleactionstest.php
>> Tokens ~/myproject/test/functional/myapp/mymoduleactionstest.php
>> Tokens ~/myproject/apps/myapp/modules/mymodule/actions/actions.class.php
>> Tokens ~/myproject/apps/myapp/modules/mymodule/templates/indexsuccess.php

Separate from the actions/,config/,lib/,templates/,validate/directory, this command creates only three files. One in the test/directory is a unit test. actions.class.php points to the default module Welcome page. The templates/indexsuccess.php file is empty.

Actions that are generated by default in the actions/actions.class.php file:

<?phpclass Mymoduleactions extends Sfactions{public function Executeindex () {$this->forward (' Default ', ' module ' );}}

For each new module, Symfony creates a default index action. He is composed of an action method called Executeindex and a template file called indexsuccess.php. We can use the following URL to browse the corresponding page:
Http://localhost/myapp_dev.php/mymodule/index
In this chapter we do not use the default index action, so we can remove the Executeindex () method from the actions.class.php file and delete the indexsuccess.php file from the templates/directory.

In addition to the command line, Symfony also provides other methods to initialize a module. One way is to create directories and files manually. In many cases, the action and template of a module means manipulating the data of a given data table. Because the required code for creating, acquiring, updating, and deleting data records from a data table is usually the same, Symfony provides a mechanism called framework to generate these code. See the 14th chapter for more information about this technology.

Add a page

In Symfony, the logic behind the page is stored in the action, while the surface is in the template. A page with no logic still needs an empty action.

Add an action

"Hello,world!" The page is accessed through a myaction action. To create this action, simply add a executemyaction method to the Mymoduleactions class, as follows:

<?phpclass Mymoduleactions extends Sfactions{public function executemyaction () {}}

The name of the action method is always the form of execute ' Xxx ' (), where the second part of the name is the name of the action, and the first letter is capitalized.

Now we can request the following URL:
Http://localhost/myapp_dev.php/mymodule/myAction

Symfony will complain about the loss of the myactionsuccess.php template. This is normal. In Symfony, a page is usually made up of a dynamic and a template.

URLs are part of the response

Symfony contains a routing system that allows us to have a complete separation between the actual action name and the URL format that needs to be called. This allows custom formatting of the URL as if he were part of the response. We are no longer constrained by the structure of the file or the parameters of the request, and the URL of an action looks like the parse we want. For example, an index action call to a module named article usually looks like this:
Http://localhost/myapp_dev.php/article/index?id=123

This URL gets a specified article from a single data. But URLs can be written in a completely different way by making minor changes in the ROUTINGYML configuration file:
Http://localhost/articles/europe/france/finance.html

Such a URL is not only for the search engine-friendly, he is also very important for users, so that users can use the address bar as a pseudo-code command to customize the query, such as the following example:
Http://localhost/articles/tagged/finance+france+euro

Symfony knows how to parse and generate URLs for users. The routing system automatically removes the requested parameter from a concise URL and makes it available for action. He also formats the hyperlinks contained in the response, making it look more concise. We will learn more about this feature in the Nineth chapter.

In short, this means that the way we name the program's actions should not be influenced by the look of their URLs, but by the functions of the actions in the program. The name of an action explains what the action actually does, and is usually a verb in the infinitive format (for example, Show,list,edit). The name of the action can be completely invisible to the end user, so you don't have to worry about using an explicit action name. We can effectively use code annotations to explain our function functions, thus making the code more readable.

Add a template

The action requires a template for encapsulation. A template is a file in the templates/directory of a module, usually named after the ending of the action and action. The default action ending is "success", so the template file created for the Myaction action should be named myactionsuccess.php.

The template contains only the performance code, so there is less PHP code to include in it. In fact, one shows "hello,world!" The page has only one line of code for the template.
<p>hello, world!</p>

If we need to run some PHP code in the template, we should avoid using the usual PHP syntax listed below. Instead, use another PHP syntax to write our templates, making the code easier to understand for non-PHP programs. Not only is the final code correct, but it also helps us to keep the complex PHP code in action, because only the control statement has the corresponding code.

The usual PHP syntax is as follows:

<p>hello, World!</p><?phpif ($test) {echo <p>. Time (). </p> ";}? >

The alternative PHP syntax is as follows:

<p>hello, world!</p><?php if ($test):? ><p><?php echo Time ();? ></p><?php endif ;?>

To pass information to a template by action

The job of the action is to complete all the complex calculations, read and test the data, and set the template variables to be output or tested. Symfony makes the properties of the action class available to the template in the global namespace. The following shows how the action passes information to the template.

Set the action properties in the action so that they are available for the template:

<?phpclass Mymoduleactions extends Sfactions{public function executemyaction () {$today = getdate (); $this->hour = $ today[' hours ';}}

Template direct access to action properties:

<p>hello, world!</p><?php if ($hour >=):? ><p>or should I say good evening? It ' s already <?php echo $hour >.</p><?php endif;?>

The template can already access some data without having to set any variables in the action. Each template can usually call $sf_context, $SF _request, $sf _params, $sf method of _user object. They contain data related to the current content, requests, request parameters, and sessions. We'll soon learn how to use them.

Collect information using the table one-way users

Forms are a good way to collect information from users. Writing forms and form elements using HTML is sometimes quite cumbersome, especially when we want to work with XTHML. We can include form elements in the Symfony template in the usual way, as shown below, but Symfony provides a helper to make the task simpler.

A template can contain the usual HTML code:

<p>hello, world!</p><?php if ($hour >=):? ><p>or should I say good evening? It's already <?php echo $hour? >.</p><?php endif?> <form method= "POST" target= "/myapp_dev.php/ Mymodule/anotheraction "><label for=" name ">what is your name?</label><input type=" text "name=" name " Id= "name" value= ""/><input type= "Submit" value= "OK"/></form>

A helper is a PHP function that is defined by Symfony in the template. He outputs HTML code and is much faster than writing the actual HTML code ourselves. Using the Symfony helper, we get the same output as the usual HTML code in the following code:

<p>hello, world!</p><?php if ($hour >=):? ><p>or should I say good evening? It's already <?php echo $hour? >.</p><?php endif;? ><?php echo Form_tag (' mymodule/anotheraction ')? ><?php Echo label_for (' name ', ' What's your name? ')? ><?php Echo Input_tag (' name ')? ><?php Echo submit_t AG (' Ok ')?></form>

If, in the code above, we think that the version of the helper is not faster than writing HTML code, then we can consider the following scenario:

<?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 will result in the following HTML output:

<select name= "Cc_type" id= "Cc_type" ><option value= "VISA" >visa</option><option value= "MAST" >mastercard</option><option value= "AMEX" selected= "selected" >american express</option>< Option value= "DISC" >Discover</option></select>

The advantage of using a helper in a template is that it speeds up the encoding and the code is clear and concise. And the price is that we need to spend time to learn. So we can not use the Symfony helper in the template, and write the code in our usual way, but it would be a huge loss.

Note that the use of short open tags (<?=, which is equivalent to <?php Echo) is not recommended for professional Web applications, because our Web server might understand multiple scripting languages and make it confusing. In addition, the short open tag does not work with the default PHP configuration and needs to be modified to activate the service. Finally, when we have to deal with XML and validation, he will make a mistake, because < has a special meaning in XML.

The form processing has a dedicated chapter to discuss, because Symfony provides many tools, a large number of helpers, to make it simple. We will learn more about helpers in the 10th chapter.

Linking to another action

We now know that there is a separation between the action name and the URL that needs to be called. So when we use the following method to create a link to another action, he will only work in the default routing system. If we decide to change the URL later, then we need to look at all the templates to change the hyperlinks.

Hyperlinks, the usual method:

<a href= "/myapp_dev.php/mymodule/anotheraction?name=anonymous" >i never say my name</a>

To avoid such trouble, we should always use the link_to () helper to create hyperlinks to our program actions. The following example demonstrates the use of a hyperlink helper.

Link_to () Helper:

<p>hello, world!</p><?php if ($hour >=):? ><p>or should I say good evening? It's already <?php echo $hour? >.</p><?php endif;? ><?php echo Form_tag (' mymodule/anotheraction ')? ><?php Echo label_for (' name ', ' What's your name? ')? ><?php Echo Input_tag (' name ')? ><?php Echo submit_t AG (' Ok ')? ><?php echo link_to (' I never say my name ', ' mymodule/anotheraction?name=anonymous ')?></form>

The HTML generated is the same as before, and the difference is that when we change our routing rules, all the templates work correctly and reformat the URLs.

The link_to () helper, like other helpers, accepts additional parameters and additional tag attributes for specific options. The following example shows an optional parameter and the generated HTML. The option parameter is either a related array or a space-delimited simple string that displays Key=value.

Most helpers receive an optional parameter:
Option argument as an associative array

<?php echo link_to (' I never say my name ', ' mymodule/anotheraction?name=anonymous ', Array (' class ' = ' Special_link ') , ' confirm ' = ' is you sure? ', ' absolute ' = true)?>
Option argument as a string<?php echo link_to (' I never say my name ', ' mymodule/anotheraction?name=anonymous ', ' class= Special_link Confirm=are you sure? Absolute=true ')? >//Both calls output the same=> <a class= "Special_link" onclick= "return confirm (' Is you sure? ') );" href= "Http://localhost/myapp_dev.php/mymodule/anotherAction/name/anonymous" >i never say my name</a>

Whenever we use a symfony helper to output an HTML tag, we can insert additional tag attributes into the optional parameters. We can write such properties using HTML 4.0, and Symfony will output in a more concise format. This is why the helper is easier to write than HTML.

Because he needs an extra parsing and conversion, the string syntax is slower than the array syntax.

Similar to the form helper, the link helper has more numbers and options. The Nineth chapter will discuss them in detail.

Information received by request

Whether the user sends information through the form (usually in the form of a POST request) or through a URL (GET request), we can get the data through the action of the Getrequestparameter () method with the Sfactions object. The following example shows how to get the value of the name parameter in Anotheraction.

The data is obtained from the request parameters in the action:

<?phpclass Mymoduleactions extends Sfactions{...public function executeanotheraction () {$this->name = $this Getrequestparameter (' name ');}}

If the processing of the data is simple, we do not even need to use the action to get the request parameters. The template can access an object named $sf_params, and he provides a get () method to get the request parameters, just like the Getrequestparameter () method in the action.

If the Executeanotheraction () method is empty, the following example shows how the anotheractionsuccess.php template file obtains the same name parameter.

The data is obtained directly from the request parameters in the template:

<p>hello, <?php Echo $sf _params->get (' name ')?>!</p>

So why not use $_post,$_get or $_request variables? Because our URLs will be formatted differently (http://localhost/articles/europe/france/finance.html), the usual PHP variables will work, and only the routing system can get the request parameters. And we want to add input filtering to prevent malicious code injection, which is only possible if we save all the request parameters in a neat parameter assembler.

$SF _params object is much more powerful than providing only one method that is equivalent to an array. For example, if we just want to detect if a request parameter exists, we can simply use the $sf_params->has () method instead of using get () to test the actual value.

Test the presence of request parameters in the template:

<?php if ($sf _params->has (' name ')):? ><p>hello, <?php Echo $sf _params->get (' name ')? >!</p ><?php else: ><p>hello, John doe!</p><?php endif;?>

As we have guessed, this can be written in a single line of code. As with most symfony, the Getrequestparameter () method in the action is the same as the $sf_params->get () in the template (which actually invokes the same principal method as the same object) Method accepts the second parameter: The default value is used if no request parameter is supplied:

<p>hello, <?php Echo $sf _params->get (' name ', ' John Doe ')?>!</p>

Summarize
In Symfony, a page consists of an action (a method prefixed with execute in the actions/actions.class.php file) and a template (a file in the templates/directory, usually ending in success.php). Their functions in the program are organized in a module. Writing a template is done by a helper, and the helper is a function that returns the HTML code provided by Symfony. And we need to treat the URL as part of the response, and the URL needs to be formatted, so we should avoid using the direct reference to the URL in the action naming or request parameter retrieval.

Once we know these basic principles, we can use Symfony to write a complete Web program. But we have a long way to go, because every task that we have to deal with in the process of program development is done by some Symfony features.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.