Quick-and-dirty ZF2: Zend\Navigation
Quick-and-dirty introduction to using Zend\Navigation in Zend Framework 2.
(1) Add Service Manager Factory
Add the following to your module configuration file (config/module.config.php
) or place it in an autoloadable file in your application's config/autoload
folder:
'service_manager' => array(
'factories' => array(
'Navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
),
);
This tells ZF2′s Serivce Manager to load the default Zend\Navigation instance factory. This factory will read a page tree from the application configuration and register a new instance of the navigation data container (Zend\Navigation\Navigation
) with the service manager under the name Navigation
.
(2) Configure Sitemap
For each module in your application you will need to construct a sitemap for the routes exposed by that module. As an example, here is one that I use with ZfcUser in my own application:
<?php
// config/autoload/nav_zfcuser.global.php
return array(
// All navigation-related configuration is collected in the 'navigation' key
'navigation' => array(
// The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key
'default' => array(
// And finally, here is where we define our page hierarchy
'account' => array(
'label' => 'Account',
'route' => 'zfcuser',
'pages' => array(
'home' => array(
'label' => 'Dashboard',
'route' => 'zfcuser',
),
'login' => array(
'label' => 'Sign In',
'route' => 'zfcuser/login',
),
'logout' => array(
'label' => 'Sign Out',
'route' => 'zfcuser/logout',
),
'register' => array(
'label' => 'Register',
'route' => 'zfcuser/register',
),
),
),
),
),
);
(3) Using the View Helpers
Now that you’ve set up the necessary configuration, all that’s left to do is use it! There are a number of bundled view helpers which you can use to inject navigation components into your views.
Example: Breadcrumbs
To render breadcrumbs add the following line to one of your views (I put it in my application’s layout view):
<?php echo $this->navigation('Navigation')->breadcrumbs(); ?>
Example: Menu
To render a sidebar navigation menu, add the following line to the location in your view script where you want the menu rendered:
<?php echo $this->navigation('Navigation')->menu(); ?>
This view helper also provides additional methods for altering the output. For example, to display only the active branch of the menu, append the call setOnlyActiveBranch(true) like so:
<?php echo $this->navigation('Navigation')->menu()->setOnlyActiveBranch(true); ?>