Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 16 ■ ADVANCED ZEND FRAMEWORK^249

This produces a stdClass object, with a property for x. See Chapter 18 for coverage of Ajax,
JSON, and the PHP JSON extension.

Customizing Routes


The previous chapter introduced the Zend Framework’s front controller. This controller is fairly
rigid in the URL format that controls routing. However, the designers of the Zend Framework
realized that it is sometimes necessary to deviate from this typical structure—for example, to
port an application with an existing structure or to create a multilingual site.
By using the rewrite router, you can add routes to the defaults or even override routes
completely. Listing 16-13 shows how to integrate the rewrite router with your application, but
without changing any functionality. Replace the following code in your bootstrap file from the
previous chapter:

$front = Zend_Controller_Front::getInstance();
$front->throwExceptions(true);
$front->run(APP_PATH. '/application/controllers');

with the code shown in Listing 16-13.

Listing 16-13. Bootstrapping the Rewrite Router (in index.php)

$router = new Zend_Controller_Router_Rewrite();
$front = Zend_Controller_Front::getInstance();
$front->setRouter($router);
$front->run(APP_PATH. '/application/controllers');

At this point, the rewrite router is engaged but is not overriding any functionality. Call
$router->addRoute() to add the override to the defaults. The format for a route is instantiated
through the Zend_Controller_Router_Route class and is fairly straightforward. Listing 16-14
demonstrates a translation of the route /product/view/productId/1 into /product/view/1.

Listing 16-14. Rewrite Routing

$route = new Zend_Controller_Router_Route(
'/product/view/:productId, array(
'controller' => 'product',
'action' => 'view',
'productId' => false
)
);
$router->addRoute('viewproduct', $route);

In this example, the controller and action are hard-set, and the productId parameter is
optional and defaults to a Boolean value of false. From the action controller perspective, the
productId value is still a parameter and is accessed as before. The only thing that has changed
is the URL.

McArthur_819-9C16.fm Page 249 Friday, February 29, 2008 5:07 PM

Free download pdf