21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Symfony2 – Franz Jordán 2011<br />

$mailer = $this->get('mailer');<br />

There are countless other services available and you are encouraged to define your own. To list<br />

all available services, use the container:debug console command:<br />

php app/console container:debug<br />

For more information, see the Service Container chapter.<br />

Managing Errors and 404 Pages<br />

When things are not found, you should play well with the HTTP protocol and return a 404<br />

response. To do this, you'll throw a special type of exception. If you're extending the base<br />

controller class, do the following:<br />

public function indexAction()<br />

{<br />

$product = // retrieve the object from database<br />

if (!$product) {<br />

throw $this->createNotFoundException('The product does not exist');<br />

}<br />

return $this->render(...);<br />

}<br />

The createNotFoundException() method creates a<br />

special NotFoundHttpException object, which ultimately triggers a 404 HTTP response<br />

inside Symfony.<br />

Of course, you're free to throw any Exception class in your controller - Symfony2 will<br />

automatically return a 500 HTTP response code.<br />

throw new \Exception('Something went wrong!');<br />

In every case, a styled error page is shown to the end user and a full debug error page is shown<br />

to the developer (when viewing the page in debug mode). Both of these error pages can be<br />

customized. For details, read the "How to customize Error Pages" cookbook recipe.<br />

Managing the Session<br />

Symfony2 provides a nice session object that you can use to store information about the user (be<br />

it a real person using a browser, a bot, or a web service) between requests. By default, Symfony2<br />

stores the attributes in a cookie by using the native PHP sessions.<br />

Storing and retrieving information from the session can be easily achieved from any controller:<br />

$session = $this->getRequest()->getSession();<br />

// store an attribute for reuse during a later user request<br />

$session->set('foo', 'bar');<br />

// in another controller for another request<br />

$foo = $session->get('foo');<br />

// set the user locale<br />

52

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!