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:
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.