Home  >  Article  >  Backend Development  >  Detailed explanation of basic creation examples of Symfony pages, detailed explanation of symfony examples_PHP tutorial

Detailed explanation of basic creation examples of Symfony pages, detailed explanation of symfony examples_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:09:01843browse

Detailed explanation of basic creation examples of Symfony pages, detailed explanation of symfony examples

This article analyzes the basic creation methods of Symfony pages through examples. Share it with everyone for your reference. The details are as follows:

Here we will learn how to create a module, which is a structural element that organizes a page. At the same time, we will also learn how to create a page that is divided into an action and a template. The reason why it is divided into actions and templates is because of the MVC pattern. Links and recognition are basic page interactions, and we'll learn how to insert these elements into templates and handle them in actions.

Create a module framework

Symfony organizes pages into modules. Before creating a page, we need to create a module and initialize it to an empty shell with a file structure that Symfony can recognize.

Symfony command line automates the creation of modules. We just need to call the init-module task and use the program name and module name as parameters. After creating a myapp program, to add a mymodule module to this program, we can enter the following command:

Copy code 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/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

Separated from the actions/,config/,lib/,templates/,validate/ directories, this command only creates three files. The one located in the test/ directory is the unit test. actions.class.php points to the default module welcome page. The templates/indexSuccess.php file is empty.

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

Copy code The code is as follows:
class mymoduleActions extends sfActions
{
Public function executeIndex()
{
             $this->forward('default', 'module');
}
}
?>

For every new module, Symfony creates a default index action. It consists of an action method named executeIndex and a template file named indexSuccess.php. We can browse the corresponding page through the following URL:
http://localhost/myapp_dev.php/mymodule/index
We are not using 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 also provides other methods to initialize a module. One method is to create directories and files manually. In many cases, a module's actions and templates are meant to manipulate data from a given data table. Because the necessary code to create, get, update, and delete data records from a data table is usually the same, Symfony provides a mechanism called a framework for us to generate this code. We will continue to introduce it later.

Add a page

In Symfony, the logic behind the page is stored in actions, while the surface is in templates. Pages without logic still require an empty action.

Add an action

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

Copy code The code is as follows:
class mymoduleActions extends sfActions
{
Public function executeMyAction()
{
}
}

The name of an action method is always in 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 missing myActionSuccess.php template. This is normal. In Symfony, a page is usually composed of an action and a template.

URL is part of the response

Symfony includes 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 for a custom URL to be formatted as if it were part of the response. We are no longer limited by the structure of the file or the parameter data of the request, and the URL of an action looks the way we want it to resolve. 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 retrieves a specified article from a data. But the URL can be written in a completely different way by making some small changes in the routingyml configuration file:
http://localhost/articles/europe/france/finance.html

Such a URL is not only friendly to search engines, it is also very important for users, so that users can use the address bar as a pseudocode command to customize queries, 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 will automatically strip the requested parameters from a compact URL and make them available for actions. It will also format the hyperlinks contained in the response to make them look cleaner. We'll learn more about this feature in Chapter 9.

In summary, this means that the way we name our program's actions should not be influenced by what the URL that calls them looks like, but rather be controlled by the functions of the actions in our program. The name of an action explains what the action actually does, and is usually a verb in the infinitive form (such as show, list, edit). The action name can be completely invisible to the end user, so there is no need to worry about using explicit action names. We can effectively use code comments to explain our function functions, thereby making the code more readable.

Add a template

Action requires a template to encapsulate it. A template is a file located in the templates/ directory of a module, usually named after action and the suffix of action. The default action suffix is ​​"success", so the template file created for the myAction action should be named myActionSuccess.php.

The template only contains presentation code, so it should contain as little PHP code as possible. In fact, a page that displays "Hello, world!" is a template with only one line of code.

Copy code The code is as follows:

Hello, world!

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

The usual PHP syntax is as follows:

Copy code The code is as follows:

Hello, world!



if ($test)
{
echo "

".time()."

";
}
 
?>

The alternative PHP syntax is as follows:

Copy code The code is as follows:

Hello, world!






Transmitting information from actions to templates

The action's job is to complete all complex calculations, data reading and testing, and set template variables to be output or tested. Symfony makes action class properties available to templates in the global namespace. The following shows how information is passed from an action to a template.

Set action attributes in an action to make it available to templates:

Copy code The code is as follows:

class mymoduleActions extends sfActions
{
Public function executeMyAction()
{
           $today = getdate();
$this->hour = $today['hours'];
}
}

Template directly accesses action attributes:

Copy code The code is as follows:

Hello, world!


= 18): ?>

Or should I say good evening? It's already .


Templates can already access some data without setting any variables in the action. Each template can usually call methods of $sf_context, $sf_request, $sf_params, $sf_user objects. They contain data related to the current content, request, request parameters, and session. We will soon learn their usage.

Use forms to collect information from users

Forms are a great way to collect information from users. Writing forms and form elements in HTML can sometimes be quite cumbersome, especially when we want to work with XTHML. We can include form elements in Symfony templates in the usual way, as shown below, but Symfony provides helpers to make this task easier.

Templates can contain the usual HTML code:

Copy code The code is as follows:

Hello, world!


= 18): ?>

Or should I say good evening? It's already .







A helper is a Symfony-defined PHP function used in a template. It outputs HTML code much faster than writing the actual HTML code ourselves. Using the Symfony helper, we get the same output as the usual HTML code above with the following code:

Copy code The code is as follows:

Hello, world!


= 18): ?>

Or should I say good evening? It's already .







If in the above code, we think that using the helper version will not be faster than writing HTML code, then we can consider the following situation:

Copy code The code is as follows:
$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 The code is as follows:

The advantage of using helpers in templates is that it speeds up coding and makes the code clear and concise. The price is that we need to spend time learning. So we could not use Symfony helpers in our templates and write the code in our usual way, but this would be a huge loss.

Note that the use of short open tags (

Form handling has its own chapter, because Symfony provides many tools, mostly helpers, to make it easy. We'll learn more about helpers in Chapter 10.

Link 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, it will only work in the default routing system. If we later decide to change the look of the URL, then we will need to look at all templates to change the hyperlink.

Hyperlink, usual method:

Copy code The code is as follows:

I never say my name

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

link_to() helper:

Copy code The code is as follows:

Hello, world!


= 18): ?>

Or should I say good evening? It's already .








The generated HTML is the same as before, except that when we change our routing rules, all templates will work correctly and the URL will be reformatted.

The link_to() helper, like other helpers, accepts additional arguments for certain options and additional label attributes. The example below shows an optional parameter and the generated HTML. The options parameter is either an associated array or a simple string separated by spaces showing key=value.

Most helpers accept an optional argument:

Copy code The code is as follows:
// Option argument as an associative array
array(
'class' => 'special_link',
'confirm' => 'Are you sure?',
           'absolute' => true
)) ?>
 
// Option argument as a string
'class=special_link confirm=Are you sure? absolute=true') ?>
                                                                            // Both calls output the same
=> href="http://localhost/myapp_dev.php/mymodule/anotherAction/name/anonymous">
I never say my name

Any time we use a Symfony helper to output an HTML markup, we can insert additional markup attributes in optional parameters. We can use HTML 4.0 to write such attributes, and Symfony will output it in a more concise format. This is why helpers are easier to write than HTML.

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

Similar to form helpers, link helpers have a greater number and options.

Get information by request

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

Get data from request parameters in the action:

Copy code The code is as follows:

class mymoduleActions extends sfActions
{
...

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

If the data processing is simple, we don't even need to use actions to get the request parameters. The template can access an object named $sf_params, which 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 can get the same name parameter.

Get data directly from request parameters in the template:

Copy code The code is as follows:

Hello, get('name') ?> ;!

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

The $sf_params object is much more powerful than just providing a method equivalent to an array. For example, if we just want to check whether 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:

Copy code The code is as follows:
has('name')): ?>

Hello, get('name') ?>!



Hello, John Doe!


We already guessed, this can be written in a single line of code. Like most get methods in Symfony, the getRequestParameter() method in the action and the $sf_params->get() method in the template (actually calling the same main method of the same object) accept a second parameter: if there is no Provide request parameters and use default values:

Copy code The code is as follows:

Hello, get('name', 'John Doe') ?>!

Summary

In Symfony, a page is composed 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 with Success.php) of. They are generally organized into modules as functions in the program. Writing templates is done by helpers, which are functions provided by Symfony that return HTML code. We need to treat the URL as part of the response, and the URL needs to be formatted, so we should avoid using direct references to the URL or request parameter retrieval in action naming.

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 handle during program development is completed by some Symfony features.

I hope this article will be helpful to everyone’s symfony framework programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/947924.htmlTechArticleDetailed explanation of basic creation examples of Symfony pages, detailed explanation of symfony examples. This article analyzes the basic creation methods of Symfony pages. Share it with everyone for your reference. The details are as follows: Here we...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn