ZF2, create dynamic menu on module initialization

I have a menu that I need to create dynamically (some blog pages are added from the database). ZF2 Dynamic Menu with Zend \ Navigation \ Navigation describes how to do this for a single controller / action.

But how should this be done for all requests, at the time of module initialization?

I need at least a routeMatch object (to get the language parameter) and I saw below to get this:

    public function onBootstrap(EventInterface $e) 
    { 
        $app = $e->getApplication(); 
        $em  = $app->getEventManager(); 

        $em->attach(MvcEvent::EVENT_ROUTE, function($e) { 
            $routeMatch = $e->getRouteMatch();
        }); 
    }

      

But the docs say:

"the onBootstrap () method is called for every module that implements this function, on every page request, and should only be used for light tasks such as registering event listeners."

What would be the best place and way to initialize dynamic navigation (or other more complex logic) in Zend Framework 2?

+3


source to share


1 answer


The right place is really bootstrap to do this kind of thing. Keep in mind that the code runs on load on every request, so keep it as light as possible. If you want to inject navigation, try caching the navigation structure from your database and injecting the version from the cache.

I made this behavior in ensemble . It fetches data from a database to dynamically build routes and based on the routes the navigation structure is built on. Routes and navigation are injected respectively into the router and navigation container, so when the application is submitted it appears that nothing is different from a "normal" request with routes configured in the .config.php module.



For some examples, you should check out the kernel currently only available with the Doctrine adapter (Zend \ Db coming soon). It registers listeners early in the connection, parses the database results in the route and navigation structure, and can be cached for better performance.

If you need more specific information, please update your question to learn more about what you missed in the larger picture.

+1


source







All Articles