Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^250) CHAPTER 16 ■ ADVANCED ZEND FRAMEWORK
It is also important to realize that this approach does not replace the default routing rules.
If you want to define an overall replacement to the routing system, the framework provides the
removeDefaultRoutes() method for this purpose.
The class for instantiating the format for the route has this form:
Zend_Controller_Router_Route($route, $defaults, $format)
with the following parameters:
$route: Anything prefixed with a colon is a variable until terminated with a slash. There are
three reserved variables: :module, :controller, and :action. These allow you to specify a
mapping for which module, controller, and action should be called.
$defaults: The second parameter is an array of defaults. This is useful when you want a
static URL but still need to map onto a controller and action. It is also useful to default
parameters to false where they are optional.
$format: When a parameter is not optional, the final format array can be used to provide
additional routing. The format is a key/value array, where the key is the parameter name
and the value is a regular expression that the parameter must pass to match the route. This
is not for validation of the data, as that can lead to unfortunate default routing, but instead
to allow you to differentiate between two similar but different routes.
Consider the routes /product/view/ProPHP and /product/view/1. How would you write
a route to map these two routes separately to viewByName and viewById actions? The format
parameter provides this ability. The first route would be the last added, as routes in the frame-
work take a first-matched, first-used approach. This route is shown in Listing 16-15.
Listing 16-15. Format-Matching Route
$route1 = new Zend_Controller_Router_Route(
'/product/view/:productId',
array(
'controller'=>'product',
'action'=>'viewById'
),
array(
'name' => '/[0-9]+/';
)
);
Because this route will not be matched if there is anything but a number as the productId,
the logic will fall through to the next route if the productId is actually a name. Then to catch the
viewByName-destined request, add a route like that shown in Listing 16-16.
McArthur_819-9C16.fm Page 250 Friday, February 29, 2008 5:07 PM

Free download pdf