Symfony(5)Controller

Symfony(5)Controller

The goal of a controller is always the same: create and return a Response object. Along the way, it might read information from the request, load a database resource, send an email, or set information on the user’s session.

1. Basic
Requests, Controller, Response Lifecycle
1. Each request is handled by a simple front controller file (app.php or app_dev.php) that bootstraps the application.
2. The Router reads information from the request, finds a route that matches that information, and reads the _controller parameter.
3. Controller executes and creates and returns a Response object;
4. The HTTP headers and content of the Response object are sent back to the client.

Route Parameters as Controller Arguments
routing.yml may put more parameters, and we can put default parameters in line of the controller configuration.
acme_hello_homepage:
    pattern:  /hello/{firstName}/{lastName}
    defaults: { _controller: AcmeHelloBundle:Default:index, color:green }

public function indexAction($firstName,$lastName, $color){
     //…snip...
}

Some Rules:
a. the order of the controller arguments does not matter, system match the names.
b. each required controller argument must match up with a routing parameter, or we can make the parameter optional
public function indexAction($firstName, $lastName, $color, $foo = ‘bar’){
     //…snip...
}

c. Not all routing parameters need to be arguments on my controller
public function indexAction($firstName, $color){}

The Request as a Controller Argument
use Symfony\Component\HttpFoundation\Request;

    public function contactAction(Request $request)
    {
        $form = $this->createForm(new ContactType());
        $form->handleRequest($request);

        if ($form->isValid()) {
            $mailer = $this->get('mailer');

            // .. setup a message and send it
            // http://symfony.com/doc/current/cookbook/email.html

            $request->getSession()->getFlashBag()->set('notice', 'Message sent!');

            return new RedirectResponse($this->generateUrl('_demo'));
        }
        return array('form' => $form->createView());
    }

The Base Controller Class
class DefaultController extends Controller{
     …snip...
}

2. Common Controller Tasks
Redirecting
public function indexAction(){
     return $this->redirect($this->generateUrl(‘homepage’));
}

homepage should be the routing name in routing.yml.

By default, the redirect() method performs a 302(temporary) redirect. To perform a 301(permanent) redirect, we put the second argument.
return $this->redirect($this->generateUrl(‘homepage’), 301);

Or we can do as follow
return new RedirectResponse($this->generateUrl('_demo'));

Forwarding
Instead of redirecting the user’s browser, system makes an internal sub-request and calls the specified controller by forwarding.

public function indexAction($name){
     $response = $this->forward(‘AcmeHelloBundle:Hello:fancy’, array(
          ‘name’ => $name,
          ‘color’  => ‘green'
     ));
     // we even can modify the response here
     return $response;
}

public function fancyAction($name, $color){}

Rending Templates
$content = $this->renderView(..snip...);
return new Response($content);

or

return $this->render('AcmeHelloBundle:Default:index.html.twig', array('name' => $name));

Accessing other Services
$templating = $this->get(‘templating’);
$router = $this->get(‘router’);
$mailer = $this->get(‘mailer’);

List all the services we have
>php app/console container:debug

3. Managing Errors and 404 Pages
Based from the base controller
public function indexAction(){
     //retrieve the object from db
     $product = …;
     if(!$product){
          throw $this->createNotFoundException(‘The product does not exist’);
     }
     …snip...
}

throw new \Exception(‘Went Wrong!’);

4. Managing the Session
Symfony2 stores the attributes in a cookie by using the native PHP sessions.

Sessions
public function indexAction(Request $request){
     $session = $request->getSession();

     $session->set(‘foo’, ‘bar’);
     
     $foobar = $session->get(‘foobar’);

     $filters = $session->get(‘filters’, array()); //default value, empty array()
}

Flash Messages
if($form->isValid()){
     $request->getSession()->getFlashBag()->set('notice', 'Message sent!');
     return $this->redirect(..snip…);
}

Twig
{% for flashMessage in app.session.flashbag.get(’notice’) %}
     <div class=“flash-notice”> {{ flashMessage }} </div>
{% endor %}

The Response Object
$response = new Response(‘Hello’.$name, Response::HTTP_OK);

response = new Response(json_encode(array(’name’=>$name)));
response->headers->set(‘Content-Type’, ‘application/json’);

JsonResponse for json, BinaryFileResponse for file.

The Request Object
$request->query->get(‘page’);
$request->request->get(‘page’);


References:
http://symfony.com/doc/2.4/book/controller.html

你可能感兴趣的:(controller)