This example describes the Symfony2 controller usage. Share to everyone for your reference, specific as follows:
A controller is a PHP function you create that receives HTTP requests and creates and returns an HTTP reply (Response). The Reply object (Response) can be an HTML page, an XML document, a serialized JSON array, a picture, a redirect, a 404 error, or whatever you want. Controller can contain any logic needed to render the content of your page.
Here is a controller simplest example of simply printing a Hello world!
Use Symfony\component\httpfoundation\response;
Public Function helloaction ()
{return
new Response (' Hello world! ');
}
The ultimate goal of 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. In all cases, however, Controller will eventually return a response object and be distributed to the client.
such as the following:
Controller a prepares a response object to represent the content of the site homepage.
Controller B reads the slug parameter from request to load a blog content from the database and creates a response object to display the 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 that reads form information from the Request object, saves contact information to the database, and sends it to the administrator. Finally, it creates a response object to redirect the client browser to the Contact form thank you page.
Requests,controller, Response's life cycle
Each request that is processed in the SYMFONY2 project passes through the same simple life cycle. The framework is responsible for repetitive tasks and ultimately executes a controller that will contain your application code: Controller
1. Each request will be processed by a unified front-end controller file (e.g., app.php, or app_dev.php), which will launch the application.
2.Router reads the URI information from the request and finds the route that matches it, reading the _controller parameter from the route.
3. The controller of the matching successful route is executed, and the code in controller creates and returns a response object.
The 4.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 way to map a URL to the controller.
Note: Although from the name point of view, the front-end controller and controller similar, in fact, they are different.
A front-end controller is a php file stored in a web directory, and many of the request will be redirected through it. Each application will have a product front-end controller app.php and a developed front-end controller app_dev.php. You don't need to edit, view or worry about them.
Look at a simple controller: any PHP callable content (such as a function, object method, or a closure) can be a controller. In Symfongy2, a controller is usually a single method in the Controller object. Controllers is also often referred to as actions.
src/acme/hellobundle/controller/hellocontroller.php
namespace Acme\hellobundle\controller;
Use Symfony\component\httpfoundation\response;
Class Hellocontroller
{public
function indexaction ($name)
{return
new Response ('
Note that in this example controller is the Indexaction method, which exists in the Controller class (Hellocontroller). Do not confuse the definition of a controller class (Hellocontroller) just to facilitate the organization of multiple controllers/actions together. In general, a controller class can have multiple controllers/actions.
The controller in the example above are fairly simple:
The namespace line is Symfony2 uses the PHP5.3 namespace feature to specify the namespace for the entire controller class.
The Use keyword imports the response class, which is what our controller must return.
The controller class name is defined by the name appended to the controller, but only the previous part is its real name, and for the sake of unification, the controller is added in the following uniform. The previous section is only taken when routing configuration.
Each method in the controller class that is used for the true controller is added a uniform suffix action, and we will only take the previous part and ignore the action when configuring its route. Map it to a URL.
The end of each controller method inevitably creates a response object and returns it.
Map a URL to a controller method:
The Controller method in the example above returns a simple HTML page. If you want to access the page in a browser, you need to create a route for it and map it to a URL of a particular pattern.
# app/config/routing.yml
Hello: 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 think Url/hello/ryan will be mapped to Hellocontroller::indexaction () controller and pass Ryan to the $name variable.
Creating a so-called page, in fact, is to create a controller method and a related route.
Note the presentation syntax we use to point to the controller method: AcmeHelloBundle:Hello:index
Symfony2 uses a very flexible string declaration to point to different controller. It tells Symfony2 to look for a class called Hellocontroller in a bundle named Acmehellobundle, and to execute its indexaction () method. In this example, our routing configuration is written directly in the app/config/directory, and a better way to organize your routing is to put your route into your own bundle.
Routing parameters as Controller methods parametric
You already have. _controller parameter AcmeHelloBundle:Hello:index points to a method in Acmehellobundle named Hellocontroller::indexaction (). Interestingly, the parameters in the route are passed to the method.
<?php
//src/acme/hellobundle/controller/hellocontroller.php
namespace Acme\hellobundle\controller;
Use Symfony\bundle\frameworkbundle\controller\controller;
Class Hellocontroller extends Controller
{public
function indexaction ($name)
{
//...
}
}
The Controller method in the example above has a unique parameter $name that corresponds to the {name} placeholder name defined in route. In fact, when you execute your controller, SYMFONY2 will match every parameter in controller and route.
If I modify the routing definition of Hello:
YAML format:
# app/config/routing.yml
Hello: 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 ',))
;
This is the time to get these parametric in controller:
Public Function indexaction ($first _name, $last _name, $color)
{
//...
}
note Whether placeholder variables or default value variables in the route definition are converted to the input variables of the Controller method. When a route match succeeds, it merges placeholders and defaults to an array to controller. Mapping route parameters to controller parameters is very simple and flexible. They do not match the order from route to controller. Symfony can map the name of the parameter variable in the route to the variable name in the Controller method signature. For example, {last_name} => $last _name, regardless of the order of arrangement.
The parameters in the Controller method must match the controller method defined by the Hello route below the parameters defined in route will throw an exception:
Public Function indexaction ($last _name, $color, $first _name)
{
//...
}
If we turn the $foo variable into an optional variable, then we don't throw the exception.
Public Function indexaction ($first _name, $last _name, $color, $foo)
{
//.
}
Not every parameter defined in route needs to have a corresponding signature parameter in the controller, such as the {$last _name defined in Hello route if it doesn't make any sense to you, you can omit it from the controller.
Public Function indexaction ($first _name, $color)
{
//.
}
Conversely, if you define a variable in the controller signature and are not an optional variable, then the corresponding parameter must be defined in the route.
There is a special parameter _route in the route definition that matches the name of route (as in the previous example, hello). Although not commonly used, it can also be used as a parametric of the controller method.
Request as a Controller method for signing variables
For convenience, you may let Symfony pass your request object as an argument to your controller method. This is especially handy when you're dealing with 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 that includes some common controller tasks and gives your controller class access to any resources you need. By inheriting the class, you can get many help methods.
src/acme/hellobundle/controller/hellocontroller.php
namespace 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, controller does not necessarily inherit the controller base class, because its internal help methods are not required. You can also inherit symfony\component\dependencyinjection\containeraware the service container object can be accessed through the Container property. You can also define controller as a service.
Common Controller tasks:
Although controller can do anything, most controller still have to do some basic tasks over and over again. such as redirects, jumps, render templates, and access to core services.
Redirect (redirecting)
If you want to redirect your users to another page, you can use the redirect () method.
Public Function indexaction ()
{return
$this->redirect ($this->generateurl (' homepage '));
Here the GenerateURL () method is a help function that generates the corresponding URL based on the given route. By default, the redirect () method performs a 302 redirect. If you want to perform a 301 redirect, you need to modify the second parameter as follows:
Public Function indexaction ()
{return
$this->redirect ($this->generateurl (' homepage ');
The redirect () method is actually a simplified notation, and the real code is as follows:
Use Symfony\component\httpfoundation\redirectresponse;
return new Redirectresponse ($this->generateurl (' homepage '));
Jump (forwarding)
You can use the forward () method easily from one controller to another controller inside. It executes an internal child request to invoke the specified controller, so no redirection of the user's client browser is generated. The response object returned by the forward () method will also return from the original controller.
The 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 parameters as the route configuration. The passed-in array argument is used to invoke the Controller argument as the target. The same interface is used when controller is embedded in the template. The Controller method for the target invocation should be the following definition:
Public Function Fancyaction ($name, $color)
{
//... create and return a Response object
}
Just like creating a controller for a route, it doesn't matter the order of the parameters. Symfony2 will match the index key name to the method parameter name $name, even if the order is scrambled. Like other controller methods, the forward method is simply a shortcut to the Symfony2 core function. A jump can be done directly through the Http_kernel service, returning a response object.
$httpKernel = $this->container->get (' Http_kernel ');
$response = $httpKernel->forward (' AcmeHelloBundle:Hello:fancy ', Array (
' name ' => $name,
' color ' => ') Green ',
));
Render Template:
Although not necessary, most controller will eventually render a template responsible for generating HTML for controller. The Renderview () method renders a template and returns its contents. This return can be used as a creation response object for controller to return to use.
$content = $this->renderview (' AcmeHelloBundle:Hello:index.html.twig ', Array (' name ' => $name));
return new Response ($content);
The code above can be further written in the following code form:
Copy Code code as follows:
return $this->render (' AcmeHelloBundle:Hello:index.html.twig ', Array (' name ' => $name));
In both cases, the template Resources/views/hello/index.html.twig in Acmehellobundle will be rendered.
The Renderview () method is a shortcut for the following code:
$templating = $this->get (' templating ');
$content = $templating->render (' AcmeHelloBundle:Hello:index.html.twig ', Array (' name ' => $name));
Of course, you can also render templates 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 to other services
As long as you inherit the controller base class, you can access the Symfony2 service through the Get () method. Like what:
$request = $this->getrequest ();
$templating = $this->get (' templating ');
$router = $this->get (' router ');
$mailer = $this->get (' Mailer ');
There are countless services available in the Symfony2, and you are encouraged to define your own services. To view all services, you can use the Container:debug command line tool
$ php app/console Container:debug
Manage Errors and 404 pages
When something is not found, you should reset the HTTP protocol to return a 404 reply. To do this, you will throw a special type of exception. If you are inheriting the Controller base class, then:
Public Function indexaction ()
{
$product =//Retrieve the object from database
if (! $product) {
throw $th Is->createnotfoundexception (' The product does not exist ');
}
return $this->render (...);
}
The Createnotfoundexception () method creates a specific Notfoundhttpexception object that eventually triggers the 404 HTTP reply. Of course you can throw any type of exception class from your controller method, and Symfony2 will automatically return a HTTP reply code.
throw new \exception (' Something went wrong! ');
Manage session
Symfony2 provides a very good session object that you can use to store information about the user between requests. By default, Symfony2 saves properties to cookies through the session in PHP itself. It is easy to store and retrieve session information in any controller:
$session = $this->getrequest ()->getsession ();
Store a property for the user's latter request
$session->set (' foo ', ' Bar ');
Gets the property for another request in another controller
$foo = $session->get (' foo ');
Set the user's localized language
$session->setlocale (' fr ');
Flash message
You can store a small number of messages to the user's session for a particular request. This is useful when dealing with a form that you want to redirect and a specific message to display in the next request. This type of message is called a flash message. For example, suppose you are dealing with a form submission:
Public Function updateaction ()
{
$form = $this->createform (...);
$form->bindrequest ($this->getrequest ());
if ($form->isvalid ()) {
//Do some sort processing
$this->get (' Session ')->setflash (' Notice ', ' Your changes Saved! ');
return $this->redirect ($this->generateurl (...));
return $this->render (...);
}
In this example, after processing the request, controller sets up a notice flash message and redirects it. The name notice is meaningless, just to identify the message. In the next active template, 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;?>
This design allows flash messages to exist for an exact request. They are generally designed to be redirected.
Response objects
As a controller, the only thing that must be done is to return a response object.
The response object is an abstraction of the HTTP response of a PHP code.
HTTP response is a text-based message that consists of HTTP headers and content returned to the client.
Create a simple response object with the default status code of
$response = new Response (' Hello '. $name);
Creates a response object based on JSON, and the status code is also
$response = new Response (Json_encode array (' name ' => $name));
$response->headers->set (' Content-type ', ' Application/json ');
The Headers property is a Headerbag object that contains many useful methods to read and change the header information of response. The head name is standardized using Content-type equivalent to Content-type or content_type effect.
Requesting object request
In addition to the value of the route placeholder, the controller can also access the Request object if the Controller base class is inherited.
$request = $this->getrequest ();
$request->isxmlhttprequest (); Determine if AJAX requests
$request->getpreferredlanguage (' en ', ' fr '));
$request->query->get (' page '); Gets the $_get parameter
$request->request->get (' page ');//Get $_post parameter
Like the response object, the header of the request object is also stored in the Headerbag object and can be accessed easily.
Summary thinking:
Whenever you create a page, you eventually need to write some code that contains logic for it. In Symfony, this is called a controller, which is a PHP function that can be used in order to finally return a response object to the user to do whatever it takes. Simply put, you can choose to inherit a controller base class that contains a number of quick ways to perform controller common tasks. For example, 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 with the PHP program design based on Symfony framework.