A detailed explanation of the controller usage of Symfony2 learning notes and symfony2 learning notes

Source: Internet
Author: User
Tags contact form

A detailed explanation of the controller usage of Symfony2 learning notes and symfony2 learning notes

This example describes the usage of the Symfony2 controller. We will share this with you for your reference. The details are as follows:

A controller is a PHP function you have created. It receives HTTP requests and creates and returns an HTTP Response ). The Response object (Response) can be an HTML page, an XML document, a serialized JSON array, an image, a redirection, a 404 error or any content you want. The controller can contain any logic required to render your page content.

The following is the simplest example of a controller. Only a Hello world is printed!

use Symfony\Component\HttpFoundation\Response;public function helloAction(){ return new Response('Hello world!');}

The ultimate goal of the Controller is to create and return a Response object. In this way, you can read information from the request object, load database resources, send emails, or write information in the user's Session. However, in all cases, the Controller will eventually return a Response object and be distributed to the client.

For example:

Controller A prepares A Response object to express the website's homepage content.
Controller B reads the slug parameter from the Request and loads a blog content from the database and creates a Response object to display this blog. If slug does not exist in the database, it will create and return a Response object with a 404 status code.

Controller C processes a contact form. It reads the form information from the Request object, saves the contact information to the database, and sends an email to the Administrator. Finally, it creates a Response object to redirect the client browser to the contact form thanks page.

Lifecycle of Requests, Controller, and Response

Every Request processed in the Symfony2 project has passed the same simple lifecycle. The framework is responsible for repeated tasks and finally executes a controller, which will contain your application code:

1. Each Request is processed by a unified front-end controller file (such as app. php or app_dev.php), which starts the application.
2. the Router reads the URI information from the Request, finds the Route that matches it, and reads the _ controller parameter from the Route.
3. The controller of the matched route is executed. The code in the controller is created and a Response object is returned.
4. The HTTP header and the generated Response object content will be sent back to the client.

Creating a page is as easy as creating a controller. Creating a route maps a URL to the controller.

Note: although the front-end controllers and controllers are similar in name, they are actually different.
A front-end controller is a PHP file stored in the web directory, and many requests are redirected through it. Each application has a product front-end controller app. php and a development front-end controller app_dev.php. You don't need to edit them, view them or worry about them.

Look at a simple Controller: any PHP callable content (such as functions, object methods, or Closure) can become a controller. In Symfongy2, a controller is usually a single method in the controller object. Controllers is also called actions.

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

Note that in this example, the controller is the indexAction method, which exists in the controller class (HelloController. Do not confuse. The reason for defining a controller class (HelloController) is to facilitate the organization of multiple controllers/actions together. Generally, a controller class has multiple controllers/actions.

The controller in the above example is quite simple:

The Namespace row is symfony2 that uses the Namespace function of PHP5.3 to specify a Namespace for the entire controller class.
The use keyword imports the Response class, which must be returned by our controller.

The Controller class name is defined by the Controller class name, but only the previous part is the real name. To ensure uniformity, add the Controller. When configuring a route, only the preceding part is used.

In the Controller class, each method used for the real controller is added with a uniform suffix Action. Similarly, when we configure the route, we only take the previous part and ignore the Action. Map it to a URL.

At the end of each controller method, a Response object is created and returned.

Map a URL to a Controller method:

The controller Method in the preceding example returns a simple HTML page. If you want to access this page in a browser, you need to create a route for it and map it to a URL in a specific mode.

# app/config/routing.ymlhello: pattern:  /hello/{name} defaults:  { _controller: AcmeHelloBundle:Hello:index }

XML format:

<!-- app/config/routing.xml --><route id="hello" pattern="/hello/{name}"> <default key="_controller">AcmeHelloBundle:Hello:index</default></route>

PHP code format:

// app/config/routing.php$collection->add('hello', new Route('/hello/{name}', array( '_controller' => 'AcmeHelloBundle:Hello:index',)));

Now you want to map URL/hello/ryan to HelloController: indexAction () controller and pass ryan to the $ name variable.

Creating a page is actually creating a controller method and a related route.

Note that the expression syntax pointing to the controller Method: AcmeHelloBundle: Hello: index

Symfony2 uses a flexible string declaration to point to different controllers. It tells Symfony2 to find a class named HelloController in a bundle named AcmeHelloBundle and execute its indexAction () method. In this example, our route configuration is directly written in the app/config/directory. A better way to organize your routes is to put them in their respective bundle.

The route parameter is used as the Controller variable.

You have set the _ controller parameter AcmeHelloBundle: Hello: index to a method named HelloController: indexAction () in AcmeHelloBundle. It is interesting that all the parameters in the route are passed to this method.

<?php// src/Acme/HelloBundle/Controller/HelloController.phpnamespace Acme\HelloBundle\Controller;use Symfony\Bundle\FrameworkBundle\Controller\Controller;class HelloController extends Controller{ public function indexAction($name) {  // ... }}

In the preceding example, the controller method has a unique parameter $ name, which corresponds to the {name} placeholder name defined in route. In fact, when you execute your controller, Symfony2 will match every parameter in the controller and route.

If I modify the Hello route definition:

YAML format:

# app/config/routing.ymlhello: pattern:  /hello/{first_name}/{last_name} defaults:  { _controller: AcmeHelloBundle:Hello:index, color: green }

XML format:

<!-- app/config/routing.xml --><route id="hello" pattern="/hello/{first_name}/{last_name}"> <default key="_controller">AcmeHelloBundle:Hello:index</default> <default key="color">green</default></route>

PHP code format:

// app/config/routing.php$collection->add('hello', new Route('/hello/{first_name}/{last_name}', array( '_controller' => 'AcmeHelloBundle:Hello:index', 'color'  => 'green',)));

At this time, the controller can get these parameters:

public function indexAction($first_name, $last_name, $color){ // ...}

Note that both placeholder variables and default variables in the route definition are converted to the input variables of the controller method. When a route match is successful, it merges the placeholder and ults into an array and passes it to the controller. Ing route parameters to controller parameters is very simple and flexible. They do not match the order from route to controller. Symfony can map the variable names in route to the variable names in the controller Method signature. For example, {last_name }=> $ last_name has nothing to do with the order.

The parameters in the Controller method must match the parameters defined in route. The controller method defined for hello route will throw an exception:

public function indexAction($last_name, $color, $first_name){ // ..}

If we change the $ foo variable to an optional variable, no exception will be thrown.

public function indexAction($first_name, $last_name, $color, $foo){ // ..}

Not every parameter defined in route needs to have the corresponding signature parameter variable in the controller, for example, if {$ last_name} defined in hello route is meaningless to you, You can omit it in controller.

public function indexAction($first_name, $color){ // ..}

If you define a variable in the Controller signature and it is not an optional variable, the corresponding parameter must be defined in the route.

The route definition has a special parameter _ route, which matches the route name (hello in the preceding example ). Although not commonly used, it can also be used as a variable of the controller method.

Request as a Controller method signature variable

For convenience, you may have symfony pass your Request object as a parameter to your controller method. This is especially convenient for processing forms.

use Symfony\Component\HttpFoundation\Request;public function updateAction(Request $request){ $form = $this->createForm(...); $form->bindRequest($request); // ...}

Controller base class

For convenience, Symfony2 defines a Controller base class, which includes some common controller tasks and provides your controller class with access to any resources you need. By inheriting this class, you can get many help methods.

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

In Symfony, the controller does not have to inherit the Controller base class because its internal help methods are not necessary. You can also inherit the Symfony \ Component \ DependencyInjection \ ContainerAware service container object which can be accessed through the container attribute. You can also define the controller as a service.

General Controller tasks:

Although the Controller can do anything, most controllers need to repeat some basic tasks. Such as redirection, redirection, rendering templates, and access to core services.

Redirecting)

If you want to redirect your user to another page, you can use the redirect () method.

public function indexAction(){ return $this->redirect($this->generateUrl('homepage'));}

The generateUrl () method is a helper function used to generate a corresponding URL Based on the given route. By default, the redirect () method executes a 302 redirection. If you want to perform 301 redirection, You need to modify the second parameter as follows:

public function indexAction(){ return $this->redirect($this->generateUrl('homepage'), 301);}

The redirect () method is actually a simplified method. The real code is as follows:

use Symfony\Component\HttpFoundation\RedirectResponse;return new RedirectResponse($this->generateUrl('homepage'));

Forwarding)

You can use the forward () method to easily switch from one controller to another. It executes an internal sub-request to call the specified controller, so it does not generate user client browser redirection. The Response object returned by the forward () method will also be returned from the original controller.

public function indexAction($name){ $response = $this->forward('AcmeHelloBundle:Hello:fancy', array(  'name' => $name,  'color' => 'green' )); // further modify the response or return it directly return $response;}

Here, the forward () method uses the same string parameter as the route configuration. Here, the input array parameter will be used as the controller parameter for the target call. When you embed a controller into a template, the same interface is used. The controller Method of the target call should be defined as follows:

public function fancyAction($name, $color){ // ... create and return a Response object}

Just like creating a controller for a route, it has nothing to do with the order of parameters. Symfony2 matches the index key name to the method parameter name $ name, even if the order is disordered. Like other Controller-based methods, the forward method is just a quick way to write the core function symfony2. A jump can be completed directly through the http_kernel service, and a Response object is returned.

$httpKernel = $this->container->get('http_kernel');$response = $httpKernel->forward('AcmeHelloBundle:Hello:fancy', array( 'name' => $name, 'color' => 'green',));

Rendering template:

Although not necessary, most controllers will eventually render a template that is responsible for generating HTML from the controller. The renderView () method renders a template and returns its content. The returned content can be used to create a Response object for the controller to return.

$content = $this->renderView('AcmeHelloBundle:Hello:index.html.twig', array('name' => $name));return new Response($content);

The above code can be further written using the following code:
Copy codeThe Code is as follows: return $ this-> render ('acmehellobundle: Hello: index.html. twig ', array ('name' => $ name ));

In both cases, the templates Resources/views/Hello/index.html. twig in AcmeHelloBundle are rendered.

The renderview () method is a quick way to write the following code:

$templating = $this->get('templating');$content = $templating->render('AcmeHelloBundle:Hello:index.html.twig', array('name' => $name));

Of course, templates can also be rendered in subdirectories.

$ Templating-> render ('acmehellobundle: Hello/Greetings: index.html. twig ', array ('name' => $ name); // index.html. twig is stored in the Resources/views/Hello/Greetings directory.

Access Other Services

As long as it inherits the Controller base class, you can use the get () method to access the symfony2 service. For example:

$request = $this->getRequest();$templating = $this->get('templating');$router = $this->get('router');$mailer = $this->get('mailer');

There are countless available services in Symfony2, and you are also encouraged to define your own services. To view all services, you can use the container: debug command line tool.

$ php app/console container:debug

Management error and 404 page

When something is not found, you should reset the HTTP protocol and return a 404 response. To do this, you will throw a special type of exception. If you inherit the Controller base class, then:

public function indexAction(){ $product = // retrieve the object from database if (!$product) {  throw $this->createNotFoundException('The product does not exist'); } return $this->render(...);}

The createNotFoundException () method creates a specific NotFoundHttpException object, which finally triggers a 404 HTTP response. Of course, you can throw any type of Exception class from your controller method. Symfony2 will automatically return a 500 HTTP response code.

throw new \Exception('Something went wrong!');

Manage sessions

Symfony2 provides a very good Session object that you can use to store user information between requests. By default, Symfony2 saves the attribute to the cookie through the Session of PHP. It is very easy to store and retrieve Session information in any controller:

$ Session = $ this-> getRequest ()-> getSession (); // stores an attribute for the last user request $ session-> set ('foo ', 'bar'); // obtain this attribute for another request in another controller $ foo = $ session-> get ('foo '); // set your local language $ session-> setLocale ('Fr ');

Flash messages

You can store a small amount of messages to your Session for a specific request. This is useful when processing a form. You want to redirect and display a specific information in the next request. This type of message is called a Flash message. For example, assume that you process a form submission:

Public function updateAction () {$ form = $ this-> createForm (...); $ form-> bindRequest ($ this-> getRequest (); if ($ form-> isValid ()) {// do some sorting processing $ this-> get ('session ')-> setFlash ('notice', 'ur changes were saved! '); Return $ this-> redirect ($ this-> generateUrl (...);} return $ this-> render (...);}

In this example, after processing the request, the controller sets a notice flash message and redirects it. The name notice is meaningless, but it is used to identify the message. In the template of the next activity, the following code can render this notic message:

Twig

{% if app.session.hasFlash('notice') %} <div class="flash-notice">  {{ app.session.flash('notice') }} </div>{% endif %}

PHP code:

<?php if ($view['session']->hasFlash('notice')): ?> <div class="flash-notice">  <?php echo $view['session']->getFlash('notice') ?> </div><?php endif; ?>

In this design, flash messages can exist for an accurate request. They are generally designed for redirection.

Response object

As a Controller, the only thing that must be done is to return a Response object.

The Response object is a PHP code abstraction of HTTP Response.
HTTP Response is a text-based message consisting of HTTP headers and the content returned to the client.

// Create a simple Response object. The default status code is 200 $ response = new Response ('hello '. $ name, 200); // create a JSON-based Response object, the status code is also 200 $ response = new Response (json_encode (array ('name' => $ name); $ response-> headers-> set ('content-type ', 'application/json ');

The headers attribute is a HeaderBag object, which contains many useful methods to read and change the header information of Response. The header name is standardized and the Content-Type is equivalent to the content-type or content_type.

Request object

In addition to the value of the placeholder routing, if the Controller class is inherited, the controller can also access the Request object.

$ Request = $ this-> getRequest (); $ request-> isXmlHttpRequest (); // determine whether an Ajax request is made $ request-> getPreferredLanguage (array ('en ', 'Fr '); $ request-> query-> get ('page '); // obtain the $ _ GET parameter $ request-> get ('page'); // obtain the $ _ POST Parameter

Like the Response object, the Request object header is stored in the HeaderBag object for convenient access.

Summary:

Whenever you create a page, you need to write logic-containing code for it. In Symfony, this is called a controller, which is a PHP function. It can return a Response object for the user to do whatever he needs. Simply put, you can choose to inherit a Controller base class, which contains many shortcuts for executing General controller tasks. For example, if you do not want to write HTML code to your controller, you can use the render () method to render and return a template content.

I hope this article will help you design PHP programs based on the Symfony framework.

Articles you may be interested in:
  • Symfony2 joint query Implementation Method
  • Symfony2 create page instance details
  • Analysis on date usage in twig of symfony2.4
  • Session and cookie usage in Symfony2
  • Summary of how Symfony2 can obtain data from the database
  • Symfony2 framework learning notes
  • Symfony2 Study Notes plugin format Analysis
  • System Route details for Symfony2 Study Notes
  • Template usage of Symfony2 learning notes
  • How to install a third-party Bundles instance in Symfony2
  • Symfony2 function usage Example Analysis

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.