Instance details on the Symfony2 create page and symfony2 instance details

Source: Internet
Author: User
Tags php template

Instance details on the Symfony2 create page and symfony2 instance details

This example describes how to create a page in Symfony2. We will share this with you for your reference. The details are as follows:

Create a page in Symfony2 in two steps:

1. Create a route: A route defines the URI (such as/about) of your page and the controller (PHP function) to be executed ). When the incoming request URL matches the route, Symfony2 executes the specified controller;

2. Create a controller: The controller is a PHP function that accepts incoming requests and converts them to the Response object of Symfony2.

We like this simple implementation because it conforms to the way the Web works. Every Web interaction starts with an HTTP request. An application's task is to simply interpret the request and return the corresponding HTTP response. Symfony2 follows this principle and provides you with tools to ensure that your application remains well organized as its users and complexity grow.

"Hello Symfony2" Page

Let's start with the classic "hello, world" program. After we finish, you can get a greeting by visiting the following URL:

http://localhost/app_dev.php/hello/Symfony

In fact, you can replace Symfony with another name to greet you. To create this page, we just need to perform the following two steps:

This tutorial assumes that you have downloaded Symfony2 and configured the Web server. The above URL assumes that localhost points to your new Symfony2 project. For installation details, see install Symfony2.

Create Bundle

Before you start, you need to create a Bundle. In Symfony2, Bundle is equivalent to a plug-in. All the code in your application must be placed in Bundle. Bundle is just a directory (with a PHP namespace), and its content is related to a specific function (see Bundle System ). Run the following command to create AcmeStudyBundle (a game created in this chapter ).

php app/console Acme/StudyBundle[/]

Next, add the following statement to the app/autoloader. php file to ensure that the Acme namespace is guided (see the automatic loading Section ):

$loader->registerNamespaces(array(  'Acme' => __DIR__.'/../src',  // ...));

Finally, initialize the Bundle in the registerBundles () method of the app/AppKernel. php file.

// app/AppKernel.phppublic function registerBundles(){  $bundles = array(    // ...    new Acme\StudyBundle\AcmeStudyBundle(),  );  // ...  return $bundles;}

Now you have set your Bundle and can build your application in your Bundle.

Create a route

By default, the route configuration file of Symfony2 is stored in the app/config/routing. yml directory. All configuration files in Symfony2 can also be written in PHP or XML format.

# app/config/routing.ymlhomepage:  pattern: /  defaults: { _controller: FrameworkBundle:Default:index }hello:  resource: "@AcmeStudyBundle/Resources/config/routing.yml"

The first few lines of the routing configuration file define the code called by the user request "/" (homepage) resource. What's more interesting is the last part, it imports other route configuration files located in AcmeStudyBundle.

# src/Acme/StudyBundle/Resources/config/routing.ymlhello:  pattern: /hello/{name}  defaults: { _controller: AcmeStudyBundle:Hello:index }

A route consists of two basic parts: pattern (pattern) determines which URI matches the current route, and the defaults array specifies the Controller to run. The placeholder {name} in pattern is a wildcard that indicates that, for example,/hello/Ryan,/hello/Fabien, or other similar Uris match the route. The {name} placeholder parameter is also sent to the Controller so that we can use its value to greet users.

The routing system has many amazing functions in creating powerful and flexible URL structures for applications. For more information, see Symfony2 Study Notes system routing details.

Create a controller

When a URI like/hello/Ryan is processed by an application, the hello route is matched and the AcmeStudyBundle: Hello: index controller is executed through the Symfony2 framework. The second step in the page creation process is to create this controller.

In fact, the controller is just a PHP function created by you and executed through Symfony2. This custom application code uses request information to build and prepare required resources. In addition to some advanced cases, the final output of the controller is the same: a Response object.

// src/Acme/StudyBundle/Controller/HelloController.phpnamespace Acme\StudyBundle\Controller;use Symfony\Component\HttpFoundation\Response;class HelloController{  public function indexAction($name)  {    return new Response('

The Controller is simple. It creates a new Response object. The first parameter of this object is the Response content returned by it (in this example, it is a small HTML page ).

Congratulations! You just got a full-featured page after creating a route and controller! If your settings are correct, your application can greet you:

http://localhost/app_dev.php/hello/Ryan

An optional but frequently used step is to create a template.

When creating a page, the controller is the main entry and key part. For more information, see the controller section.

Create Template

The template allows you to put all the presentations (such as HTML code) in a single file and reuse different blocks of the page layout. The following code replaces the HTML code in the Controller with a template.

// Src/Acme/StudyBundle/Controller/HelloController. phpnamespace Acme \ StudyBundle \ Controller; use Symfony \ Bundle \ FrameworkBundle \ Controller; class HelloController extends Controller {public function indexAction ($ name) {return $ this-> render ('acmestudybundle: Hello: index.html. twig ', array ('name' => $ name); // render the PHP template // return $ this-> render ('acmestudybundle: Hello: index.html. php ', array ('name' => $ name ));}}

To use the render () method, you must inherit the Controller class, which adds shortcuts for some common tasks.

The render () method creates a Response object that is filled with specific content and rendered using a template. Like other controllers, what you get is a Response object.

Note: There are two different rendering templates. By default, Symfony2 supports two rendering templates: Traditional PHP templates and simple and powerful Twig templates. You can either choose one of them or mix them in the same project.

The Controller renders the AcmeStudyBundle: Hello: index.html. twig template, which uses the following naming conventions:

Bundle name: Controller name: Template Name

In this example, acmestudybundleis the bundlename, hellois the controller, and index.html. twig is the Template Name.

{# src/Acme/StudyBundle/Resources/views/Hello/index.html.twig #}{% extends '::layout.html.twig' %}{% block body %}  Hello {{ name }}!{% endblock %}

Let's use the following line:
Row 2nd: extends defines a parent template, which clearly defines a layout file to be replaced;
Line 2: block the content will replace the block named body. as we know, the rendering of the block named body in layout.html. twig will be responsible for the final moment.
Parent template: layout.html. twig omitted its bundle name and controller name (so it should be replaced by two colons:). This means that the template is outside the bundle and in the app directory.

{# app/Resources/views/layout.html.twig #}<!DOCTYPE html>

The basic template file defines the HTML layout and uses the block rendering named body defined in the index.html. twig template. This also defines a partition named title. you can also choose to define it in the index.html. twig template. Since the title block is not defined in the subtemplate, the default value "Hello Application" is used ".

Templates provide powerful functions in rendering and organizing page content. They can be HTML identification language, CSS code, or something that the Controller may need to return. The template engine is only a means to achieve the goal. The goal of each controller is to return a Response object. Although the template is powerful, it is optional. It is only a tool for creating content for the Response object.

Directory structure

After learning the previous sections, you have understood the steps for creating and rendering pages in Symfony2, and started to understand the organization and structure of Symfony2. At the end of this chapter, you will learn where to find and place different types of files and why to do so.

Although the directory structure of Symfony2 is quite flexible, Symfony2 still has the same and recommended basic directory structure by default:

App/: This directory contains application configurations;
Src/: the PHP code of all projects is stored in this directory;
Vendor/: place the library files of all suppliers as agreed;
Web/: This is the web root directory, including some files accessible to the public.

WEB directory

The web root directory is the home directory of all static and public files, including images, style sheets, and javascript files. This is where the front-end controller is located.

// web/app.phprequire_once __DIR__.'/../app/bootstrap.php';require_once __DIR__.'/../app/AppKernel.php';use Symfony\Component\HttpFoundation\Request;$kernel = new AppKernel('prod', false);$kernel->handle(Request::createFromGlobals())->send();

The front-end controller (here app. php) is actually a php file that is executed when the Symfony2 application is used. Its function is to use the kernel-class AppKernel for app self-lifting.
Using a front-end controller means a more flexible and variable URL than using a traditional pure PHP program. When using a front-end controller, the URL format is as follows:

http://localhost/app.php/hello/Ryan

The front-end controller app. php is executed, and URI (/hello/Ryan) is internally routed through routing configuration. If you use Apache rewrite rules, you can enforce them without specifying app. php:

http://localhost/hello/Ryan

Although the front-end controller is indispensable for processing requests, you rarely modify or even think of it. We just mention it in the environment chapter.

App directory

As you can see in the front-end controller, the AppKernel class is the main entrance of the entire application. It is responsible for all the configurations and is saved in the app/directory.

This class must implement three methods. These methods are required for the application to understand Symfony2. You don't even have to worry about these methods at the beginning, because Symfony2 intelligently fills them up for you:

1. registerBundles (): returns all bundle arrays to be run in the application (see Bundle System );
2. registerContainerConfiguration (): The main configuration resource file that directs the application (see application configuration );
3. registerRootDir (): returns the app root directory (default value: app /)

In daily development, you will often use the app/directory. You will modify the configuration and route file in the app/config/directory (see application configuration ), the app/cache/directory will also be used as the cache directory of the application, the app/logs/directory will be used as the log directory, and the app/Resources/directory will be used as the application-level resource directory. In the following sections, you will learn

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.