A free and open-source book on Zend Framework for beginners


5.5. Literal Route Type

With Literal route type, the route match is achieved only when you have the exact match of the route string against the URL path part. You typically use the Literal type for URLs which should be short and memorable, like '/about' or '/news'.

Below, the definition of the route named "home" is presented. The "home" route is usually mapped to the "index" action of the IndexController and points to the Home page of your site:

'home' => [
    'type' => Literal::class,
    'options' => [
        'route'    => '/',
        'defaults' => [
            'controller' => Controller\IndexController::class,
            'action'     => 'index',
        ],
    ],
],

Line 2 of this example says that the route's type is Literal. The actual route matching algorithm is implemented in the Zend\Router\Http\Literal class.

Line 4 defines the route string to match against the URL path (the forward slash '/' means the empty URL part). Because we have the literal route type, the route match is achieved only when you have the exact literal path match. For example, if you have the URL "http://localhost/" or "http://localhost", it will match the '/' route string.

Lines 5-8 define the defaults, which are the parameters returned by the router if the route matches. The controller and action parameters define the controller and controller's action method which should be executed. You can also define other parameters here, if needed.

As another example of the Literal route type, let's add the '/about' route for the About page we've created earlier in the Views section of the chapter Model-View-Controller. To create the route, add the following lines right after the "home" route definition inside of your module.config.php file:

'about' => [
    'type' => Literal::class,
    'options' => [
        'route' => '/about',
        'defaults' => [
            'controller' => Controller\IndexController::class,
            'action'     => 'about',
        ],
    ],
],

If you now open the "http://localhost/about" URL in your web browser, you should see the About page.


Top