Tuesday, July 26, 2016

Friday, July 22, 2016

Accessing other Services

When extending the base controller class, you can access any Symfony service via the get()method of the Controller class. Here are several common services you might need:
1
2
3
4
5
$templating = $this->get('templating');

$router = $this->get('router');

$mailer = $this->get('mailer');
What other services exist? To list all services, use the debug:container console command:
1
$ php bin/console debug:container
For more information, see the Service Container chapter.
To get a container configuration parameter in controller you can use thegetParameter() method:
$from = $this->getParameter('app.mailer.from');

Symfony3 Render

Rendering Templates

If you're serving HTML, you'll want to render a template. The render() method renders a templateand puts that content into a Response object for you:
// renders app/Resources/views/hello/index.html.twig
return $this->render('hello/index.html.twig', array('name' => $name));
Templates can also live in deeper sub-directories. Just try to avoid creating unnecessarily deep structures:
// renders app/Resources/views/hello/greetings/index.html.twig
return $this->render('hello/greetings/index.html.twig', array(
    'name' => $name
));

Symfony3 Redirecting

Redirecting

If you want to redirect the user to another page, use the redirectToRoute() method:
1
2
3
4
5
6
7
public function indexAction()
{
    return $this->redirectToRoute('homepage');

    // redirectToRoute is equivalent to using redirect() and generateUrl() together:
    // return $this->redirect($this->generateUrl('homepage'));
}
By default, the redirectToRoute() method performs a 302 (temporary) redirect. To perform a 301 (permanent) redirect, modify the third argument:
public function indexAction()
{
    return $this->redirectToRoute('homepage', array(), 301);
}
To redirect to an external site, use redirect() and pass it the external URL:
public function indexAction()
{
    return $this->redirect('http://symfony.com/doc');
}
For more information, see the Routing chapter.
The redirectToRoute() method is simply a shortcut that creates a Response object that specializes in redirecting the user. It's equivalent to:
1
2
3
4
5
6
use Symfony\Component\HttpFoundation\RedirectResponse;

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