Detailed description of basic instance creation on the Symfony page and symfony instance _ PHP Tutorial

Source: Internet
Author: User
Tags php template
The basic instance creation details on the Symfony page, and the symfony instance details. Detailed description of basic instance creation on the Symfony page, and detailed description of symfony instance This article analyzes the basic creation methods on the Symfony page. Share it with you for your reference. Details are as follows: Here we will explain the basic instance creation details on the Symfony page, and the symfony instance details

This document describes how to create a Symfony page. Share it with you for your reference. The details are as follows:

Here we will learn how to create a module, which is a structured element of the organizational page. At the same time, we will also learn how to create a page with one action and one template. the reason why the page is divided into action and template is the MVC mode. Link and commendation are basic page interactions. we will learn how to insert these elements in the template and process them in actions.

Create a Module Framework

Symfony organizes the page as a module. 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 command line automatic processing module creation. We only need to call the init-module task and use the program name and module name as the parameter. After creating a myapp program, to add a mymodule module to the program, run the following command:

The code is 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. 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. class. php
> Tokens ~ /Myproject/apps/myapp/modules/mymodule/templates/indexSuccess. php

It is separated from the actions/, config/, lib/, templates/, and validate/Directories. 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.

The default action generated in the actions/actions. class. php file:

The code is as follows:

<? Php
Class mymoduleActions extends sfActions
{
Public function executeIndex ()
{
$ This-> forward ('default', 'module ');
}
}
?>


For each new module, Symfony creates a default index action. It is composed of an action method named executeIndex and a template file named indexSuccess. php. We can use the following URL to browse the corresponding page:
Http: // localhost/myapp_dev.php/mymodule/index
The default index action is not used 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 also provides other methods to initialize a module. One method is to manually create directories and files. In many cases, the actions and templates of a module mean to operate on the data of a given data table. Because the code required to create, retrieve, update, and delete data records from a data table is usually the same, Symfony provides a mechanism named framework to generate the code. We will continue to introduce it later.

Add a page

In Symfony, the logic behind the page is stored in the action, while the surface is in the template. An empty action is still required for a page without logic.

Add an action

"Hello, world! "The page will be accessed through a myAction action. To create this action, you only need to add the executeMyAction method to the mymoduleActions class, as shown below:

The code is as follows:

<? Php
Class mymoduleActions extends sfActions
{
Public function executeMyAction ()
{
}
}

The action method name is always in the form of execute 'XXX' (). The second part of the name is the action name, 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 composed of one action and one template.

URL is part of the response

Symfony contains a routing system that allows us to completely separate the actual action name from the URL format to be called. This allows you to customize the URL format, just as it is part of the response. We no longer limit the file structure or request parameters. the URL of an action looks like what we want to resolve. For example, calling an index action called by the article module is usually as follows:
Http: // localhost/myapp_dev.php/article/index? Id = 123

This URL is used to obtain a specified article from a piece of data. However, the URL can be written in a completely different way by making some minor changes in the routingyml configuration file:
Http: // localhost/articles/europe/france/finance.html

Such a URL is not only friendly to search engines, but also very important to users. in this way, users can use the address bar as a pseudo code command to customize queries. for 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 simple URL and makes it available for action. It also formats the hyperlinks contained in the response to make them look more concise. We will learn more about this feature in chapter 9.

In short, this means that the way we name the action of a program should not be affected by calling their URL, but by the function of the action in the program. An action name explains the actual content of an action, and is usually a verb (such as show, list, and edit) in an Infinitus format ). The action name can be completely invisible to end users, so you do not have to worry about using an explicit action name. We can effectively use code annotations to explain our function functions, so that the code can be read more.

Add a template

Action requires a template for encapsulation. A template is a file located in the templates/directory of a module. it is usually named after the word ends of actions and actions. The default action suffix is "success". Therefore, the template file created for the myAction action should be named myActionSuccess. php.

The template only contains the expressive code. Therefore, you must include as few PHP code as possible. In fact, "Hello, world!" is displayed! The page has only one line of code template.

The code is as follows:

Hello, world!

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

The common PHP syntax is as follows:

The code is as follows:

Hello, world!


<? Php

If ($ test)
{
Echo"

". Time ()."

";
}

?>

The Alternative PHP syntax is as follows:

The code is as follows:

Hello, world!


<? Php if ($ test):?>

<? Php echo time () ;?>


<? Php endif;?>



Pass information to the template by action

The action is to complete all complex calculations, read data, and test, and set the template variables to be output or tested. Symfony makes the attributes of the category class available as templates in the global namespace. The following shows how an action transmits information to a template.

Set the action attribute in the action to make the template available:

The code is as follows:

<? Php

Class mymoduleActions extends sfActions
{
Public function executeMyAction ()
{
$ Today = getdate ();
$ This-> hour = $ today ['urs'];
}
}

Direct template access action attributes:

The code is as follows:

Hello, world!


<? Php if ($ hour >=18):?>

Or shocould I say good evening? It's already <? Php echo $ hour?>.


<? Php endif;?>

The template can access some data without setting any variables in the action. Every template can call the $ sf_context, $ sf_request, $ sf_params, and $ sf_user object methods. They contain data related to the current content, requests, request parameters, and sessions. We will soon learn their usage.

Collect information from users using forms

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

The template can contain common HTML code:

The code is as follows:

Hello, world!


<? Php if ($ hour >=18):?>

Or shocould I say good evening? It's already <? Php echo $ hour?>.


<? Php endif;?>

A helper is a PHP function defined by Symfony in the template. It outputs HTML code, which is much faster than writing actual HTML code. Using the Symfony help tool, we use the following code to get the same output as the preceding common HTML code:

The code is as follows:

Hello, world!


<? Php if ($ hour >=18):?>

Or shocould I say good evening? It's already <? Php echo $ hour?>.


<? 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')?>

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

The code is as follows:

<? Php
$ Card_list = array (
'Visa '=> 'visa ',
'Mast '=> 'MasterCard ',
'Amx' => 'American Express ',
'Disc' => 'discover ');
Echo select_tag ('CC _ type', options_for_select ($ card_list, 'amex '));
?>

The following HTML output result is displayed:

The code is as follows:

Visa MasterCard American Express Discover

The benefit of the helper used in the template is that it accelerates the encoding speed, and the code is clear and concise. The cost is that we need to spend time learning. Therefore, we can not use the Symfony helper in the template and write the code in our usual way, but this is a huge loss.

Note: The usage of short open flag (<? =, Equivalent to <? Php echo) is not recommended in professional web programs, because our web servers may understand multiple scripting languages, which can confuse them. In addition, the short open tag does not work with the default PHP configuration, and you need to modify the service to activate it. Finally, when we have to process XML and verification, it will make an error because <? It has special significance in XML.

Form processing is discussed in a specific chapter, because Symfony provides many tools and a large number of helper tools to make it simple. We will learn more about the helper in chapter 10th.

Link to another action

We now know that there is a separation between the action name and the URL to be called. Therefore, when we use the following method to create a link to another action, it will only work in the default routing system. If we decide to change the URL in the future, we need to view all templates to change the hyperlink.

Hyperlink. Common method:

The code is as follows:


I never say my name

To avoid this problem, we should always use the link_to () helper to create hyperlinks for our program actions. The following example demonstrates the usage of the hyperlink helper.

Link_to () helper:

The code is as follows:

Hello, world!


<? Php if ($ hour >=18):?>

Or shocould I say good evening? It's already <? Php echo $ hour?>.


<? 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 ')?>

The generated HTML is the same as the previous one. The difference is that when we change our routing rules, all templates will work correctly and reformat the URL.

Link_to () helper, like other helper, will accept 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 simple string that is separated by spaces to display key = value.

Most Enis receive an optional parameter:

The code is 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 calloutput the same
=> Href = "http: // localhost/myapp_dev.php/mymodule/anotherAction/name/anonymous">
I never say my name

When we use a Symfony helper to output an HTML tag at any time, we can insert additional tag attributes in the optional parameters. We can use HTML 4.0 to write such an attribute, and Symfony will output it in a more concise format. This is why the helper is easier to write than HTML.

Because it requires an additional analysis and conversion, the string syntax is slower than the array syntax.

Similar to the form helper, the linked helper has more quantity and options.

Information obtained from the request

Whether users send information through forms (usually POST requests) or through URLs (GET requests), we can GET data through the getRequestParameter () action of the sfActions object. The following example shows how to obtain the name parameter value in anotherAction.

Obtain data from the request parameters in the action:

The code is as follows:

<? Php

Class mymoduleActions extends sfActions
{
...

Public function executeAnotherAction ()
{
$ This-> name = $ this-> getRequestParameter ('name ');
}
}

If data processing is simple, we do not even need to use actions to obtain request parameters. The template can access an object named $ sf_params. It provides the 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 gets the same name parameter.

In the template, data is directly obtained by request parameters:

The code is as follows:

Hello, <? Php echo $ sf_params-> get ('name')?>!

So why not use the $ _ POST, $ _ GET, or $ _ REQUEST variable? Because our URL will be formatted in different ways (http: // localhost/articles/europe/france/finance.html), the common PHP variables will take effect again, only the routing system can obtain the request parameters. However, we want to add input filtering to prevent malicious code injection. this is only possible if we save all request parameters in a simple parameter assembler.

$ Sf_params object is much more powerful than providing only one method equivalent to an array. For example, if we only want to check whether a request parameter exists, we can simply use the $ sf_params-> has () method without using get () to test the actual value.

Test the existence of request parameters in the template:

The code is as follows:

<? Php if ($ sf_params-> has ('name'):?>

Hello, <? Php echo $ sf_params-> get ('name')?>!


<? Php else:?>

Hello, John Doe!


<? Php endif;?>

As we have already guessed, this can be written in a single line of code. Like most methods in Symfony, the getRequestParameter () method in the action is the same as the $ sf_params-> get () method in the template (actually the same primary method of the same object is called) the method accepts the second parameter: if the request parameter is not provided, the default value is used:

The code is as follows:

Hello, <? Php echo $ sf_params-> get ('name', 'johndoe ')?>!

Summary

In Symfony, a page is composed of an action (actions/actions. class. A method prefixed with execute in the PHP file) and a template (a file in the templates/directory, usually Success. php end. They all organize functions in a program in a module. Templates are compiled by the help tool, and the help tool is a function provided by Symfony to return HTML code. We need to regard the URL as a part of the response, and the URL can be formatted as needed. Therefore, we should avoid using the direct reference of the URL or request parameter retrieval in the action name.

Once we understand these basic principles, we can use Symfony to compile a complete Web program. However, we still have a long way to go, because every task we need to process in the program development process is completed by some Symfony features.

I hope this article will help you design the symfony framework program.

This document analyzes the basic creation methods of the Symfony page. Share it with you for your reference. Details: here we...

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.