Table of Contents
Detailed explanation of basic creation examples of Symfony pages, detailed explanation of symfony examples
Home Backend Development PHP Tutorial 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

Jul 13, 2016 am 10:09 AM
symfony create Instantiate

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create pixel art in GIMP How to create pixel art in GIMP Feb 19, 2024 pm 03:24 PM

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

How to create a family with Gree+ How to create a family with Gree+ Mar 01, 2024 pm 12:40 PM

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

How to create a Gantt chart using Highcharts How to create a Gantt chart using Highcharts Dec 17, 2023 pm 07:23 PM

How to use Highcharts to create a Gantt chart requires specific code examples. Introduction: The Gantt chart is a chart form commonly used to display project progress and time management. It can visually display the start time, end time and progress of the task. Highcharts is a powerful JavaScript chart library that provides rich chart types and flexible configuration options. This article will introduce how to use Highcharts to create a Gantt chart and give specific code examples. 1. Highchart

How to Create a Contact Poster for Your iPhone How to Create a Contact Poster for Your iPhone Mar 02, 2024 am 11:30 AM

In iOS17, Apple has added a contact poster feature to its commonly used Phone and Contacts apps. This feature allows users to set personalized posters for each contact, making the address book more visual and personal. Contact posters can help users identify and locate specific contacts more quickly, improving user experience. Through this feature, users can add specific pictures or logos to each contact according to their preferences and needs, making the address book interface more vivid. Apple in iOS17 provides iPhone users with a novel way to express themselves, and added a personalizable contact poster. The Contact Poster feature allows you to display unique, personalized content when calling other iPhone users. you

A first look at Django: Create your first Django project using the command line A first look at Django: Create your first Django project using the command line Feb 19, 2024 am 09:56 AM

Start the journey of Django project: start from the command line and create your first Django project. Django is a powerful and flexible web application framework. It is based on Python and provides many tools and functions needed to develop web applications. This article will lead you to create your first Django project starting from the command line. Before starting, make sure you have Python and Django installed. Step 1: Create the project directory First, open the command line window and create a new directory

How to create mdf file How to create mdf file Feb 18, 2024 pm 01:36 PM

MDF file is a common database file format and it is one of the main files of Microsoft SQL Server database. In database management systems, MDF files are used to save the main data of the database, including tables, indexes, stored procedures, etc. Creating an MDF file is one of the key steps in creating a database. Some common methods will be introduced below. Using SQLServerManagementStudio(SSMS)SQLServerManag

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

How to create a WeChat group? How to create a WeChat group How to create a WeChat group? How to create a WeChat group Mar 06, 2024 pm 02:55 PM

WeChat is a mainstream chat tool. Users can communicate with friends through WeChat in a richer form. Sometimes, due to some circumstances, we need to create groups to quickly circle people, such as common classmate groups, class groups, family groups, company groups, micro-business groups, etc. Let’s learn how to create a WeChat group! How to create a WeChat group? The first method to create a WeChat group: 1. Click [+] in the upper right corner of the WeChat interface; 2. Click [Start Group Chat]; 3. Select the communication friends you want to initiate a group chat with, and click the upper right corner after selecting [Complete]; 4. Click [···] in the upper right corner of the group chat to enter the group chat setting interface; 5. After opening the group chat setting interface, click [Group Chat Name] to set the group name; 6. Click [+] or【

See all articles