Symfony The basic example of creating a page _php example

Source: Internet
Author: User
Tags anonymous php template

This article analyzes the basic creation method of Symfony page. Share to everyone for your reference. Specifically as follows:

Here we will learn how to create a module, which is a structured element of the organization's pages. At the same time we will learn how to create a page divided into one action also a template, the reason is divided into actions and templates, because of the MVC pattern. Linking and recognition are basic page interactions, and we will learn how to insert these elements into a template and process them in action.

Create a module framework

Symfony organizes the page into modules. Before we create a page, we need to create a module and initialize it to an empty shell of a symfony identifiable file structure.

The Symfony command line automates the creation of modules. All we need to do is invoke the Init-module task and use the program name as well as the module name as an argument. After creating a MyApp program, to add a MyModule module to the program, we can enter the following command:

Copy Code code as follows:
> 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 of the test/directories 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:

Copy Code code as follows:
<?php
Class 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 named indexsuccess.php. We can use the following URL to browse the appropriate page:
Http://localhost/myapp_dev.php/mymodule/index
We do not use the default index action here, 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 provides other ways to initialize a module. One way to do this is to manually create directories and files. In many cases, a module's actions and templates mean manipulating data from a given data table. Because the necessary code to create, get, update, and delete data records from a datasheet is usually the same, Symfony provides a mechanism called a framework to generate the code. We will continue to introduce the following.

Add a page

In Symfony, the logic behind the page is stored in the action, and 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:

Copy Code code as follows:
<?php
Class Mymoduleactions extends Sfactions
{
Public Function executemyaction ()
{
}
}

The name of the action method is always in the form of ' 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 losing the myactionsuccess.php template. This is normal. In Symfony, a page is usually made up of one dynamic and one 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 invoked. This allows custom formatting of the URL to be customized as if he were part of the response. We are no longer restricted to the structure of the file or to the parameters of the request, and the URL of an action looks like the parsing we want. For example, an index action call to a article module is usually as follows:
Http://localhost/myapp_dev.php/article/index?id=123

This URL gets a specified article from one data. However, 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

This URL is not only for 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 the user. The routing system automatically removes the requested parameter from a simple URL and makes it available to the action. He also formats the hyperlinks contained in the response to make them 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 affected by the way their URLs are invoked, but by the function of the action in the program. The name of an action explains what the action actually does, and is usually a verb in the infinitive format (e.g. Show,list,edit). The name of the action can be done 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 to make the code more readable.

Add a template

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

The template contains only the presentation code, so there's less PHP code to include. In fact, a display of "hello,world!" The page has only one line of code for the template.

Copy Code code as follows:
<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 complex PHP code in action, because only the control statement has the corresponding code.

The usual PHP syntax is as follows:

Copy Code code as follows:
<p>hello, world!</p>
<?php

if ($test)
{
echo "<p>". Time (). " </p> ";
}

?>

The alternate PHP syntax is as follows:

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


passing information to a template by an 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 exported 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 property in the action to make it available to the template:

Copy Code code as follows:
<?php

Class Mymoduleactions extends Sfactions
{
Public Function executemyaction ()
{
$today = getdate ();
$this->hour = $today [' hours '];
}
}

Template Direct Access Action properties:

Copy Code code as follows:
<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 already has access to some data without having to set any variables in the action. Each template can usually invoke $sf_context, $SF _request, $sf _params, $sf method of _user object. They contain data related to the current content, request, request parameters, and session. We'll learn how to use them soon.

Using tables to collect information from users

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

Templates can contain the usual HTML code:

Copy Code code as follows:
<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 defined by Symfony in a template. He outputs HTML code and is much faster than the actual HTML code we write ourselves. Using the Symfony helper, the output we get with the following code is the same as the usual HTML code above:

Copy Code code as follows:
<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 is your name? ')?>
<?php Echo input_tag (' name ')?>
<?php echo submit_tag (' Ok ')?>
</form>

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

Copy Code code as follows:
<?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:

Copy Code code as follows:
<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 benefit of the helper used in the template is the speed of coding, the clarity and simplicity of the code. And the price is to learn when we need to spend. 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 (<?=, equivalent to <?php Echo) is not recommended in professional Web applications, because our Web servers may understand multiple scripting languages, making them 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 makes a mistake because it has a special meaning in XML.

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

Link to another action

We now know that there is a separation between the action name and the URL that needs to be invoked. So we use the following way to create a link to another action that he will only work on the default routing system. If we decide to change the URL in the future, then we need to see all the templates to change the hyperlink.

Hyperlinks, the usual method:

Copy Code code as follows:
<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 shows the use of the hyperlink helper.

Link_to () Helper:

Copy Code code as follows:
<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 is your name? ')?>
<?php Echo input_tag (' name ')?>
<?php echo submit_tag (' Ok ')?>
<?php echo link_to (' I never say my name ', ' mymodule/anotheraction?name=anonymous ')?>
</form>

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

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

Most helpers receive an optional parameter:

Copy Code code as follows:
Option argument as an associative array
<?php echo link_to (' I never say my name ', ' mymodule/anotheraction?name=anonymous ',
Array
' Class ' => ' Special_link ',
' Confirm ' => ' Are 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 to confirm (' Are you sure? ');"
href= "Http://localhost/myapp_dev.php/mymodule/anotherAction/name/anonymous" >
I never say my name</a>

Any time we use a symfony helper to output an HTML tag, we can insert additional tag attributes in the optional arguments. We can use HTML 4.0 to write such a property, and Symfony will output in a more concise format. That's why helpers are easier to write than HTML.

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

Similar to the form helper, the link helper has more numbers and options.

Get information from request

Regardless of whether the user sends information through the form (usually as a POST request) or through a URL (GET request), we can fetch 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.

Data is obtained from the request parameter in the action:

Copy Code code as follows:
<?php

Class Mymoduleactions extends Sfactions
{
...

Public Function executeanotheraction ()
{
$this->name = $this->getrequestparameter (' name ');
}
}

If the data processing is simple, we do not even need to use the action to get the request parameters. A template can access an object named $sf_params, and he provides a get () method to obtain 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 gets the same name parameter.

Data is obtained directly from the request parameter in the template:

Copy Code code as follows:
<p>hello, <?php Echo $sf _params->get (' name ')?>!</p>

So why not use $_post,$_get or $_request variables? Because our URLs will be formatted in different ways (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 block malicious code injection, which is only possible if we save all the request parameters in a simple parametric 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 whether a request parameter exists, we can simply use the $sf_params->has () method instead of using get () to test the actual value.

To test the existence of the request parameter in the template:

Copy Code code as follows:
<?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 acquisition methods in Symfony, the Getrequestparameter () method in the action and the $sf_params->get () in the template (which actually calls the same main method of the same object) Method accepts the second parameter: The default value is used if no request parameter is supplied:

Copy Code code as follows:
<p>hello, <?php Echo $sf _params->get (' name ', ' John Doe ')?>!</p>

Summarize

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

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

I hope this article will be helpful to everyone's Symfony framework program design.

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.