Redirecting to a 404 Error Page in Zend Framework 2

Written by James Mansson on December 16, 2012 Categories: Zend Framework 2

I’ve recently been playing around with Zend Framework version 2, with an eye to using it on live projects in the near future. As someone who is very familiar with the original Zend Framework (I’ve used it since version 1.0), one question that continually arises is how to do the various things I already do in version 1 in version 2. A simple example of this is the redirecting to a 404 error page. The framework automatically does this if the user selects a route that it doesn’t recognise. However, there are also situations where the route is valid, but the correct response is a 404 page, as the user is after a resource that does not exist. For instance, it may be conventional on your website to have the URLs of product pages in the form http://www.example.com/products/view/page/[page-name], where [page-name] maps against an entry in the database or a file that represents a particular product page. If for some reason the value of [page-name] doesn’t map properly (e.g. the page has been removed), it is appropriate to bring up a 404 page.

In Zend Framework 1, the way I used to do this was to throw an exception of type Zend_Controller_Action_Exception, like this:

throw new Zend_Controller_Action_Exception
 ('Page not found', 404);

This method is not the recommended way in Zend Framework 2. A quick search via Google threw up this article, which revealed that the proper approach is the following:

$this->getResponse()->setStatusCode(404);
return;

As the author of the article notes tersely, this will trigger the framework’s RouteNotFoundStrategy, which will lead to the user being redirected to the 404 page. Note that the return statement can be omitted if there are no following statements.

1 Comment on Redirecting to a 404 Error Page in Zend Framework 2

1 Comment

  • James, thanks for linking to my blog post.

    From your blog, it looks like we have similar interests. I am one of the organisers of PHP Hampshire (http://phphants.co.uk). We have an event coming up in Portsmouth at the end of July if you are interested. If its too far, perhaps could join in on the mailing list.

    If you do, be sure to say “Hi”.

Leave a Reply

Your email address will not be published. Required fields are marked *