ZF2 - Injecting pages to navigation before controller is called

前端 未结 2 1344
南方客
南方客 2020-12-21 12:30

I\'m creating a dynamic Application in which the content is added through a CMS. Inside the CMS, I\'m setting a db entry which states what module to use for each content pag

2条回答
  •  独厮守ぢ
    2020-12-21 12:40

    Responding to your comment on @Crisp's answer, and for future googlers, I'll explain how to do something similar for routing.

    Typically you would want to create a custom router that can match URLs to the pages in your database, similarly to the standard Segment router. To do this, you will have to implement the Zend\Mvc\Router\RouteInterface interface. For example:

    namespace Application\Router;
    
    use Zend\Mvc\Router\RouteInterface;
    use Application\Model\CMSTable;
    
    class CmsRoute implements RouteInterface, ServiceLocatorAwareInterface
    {
        protected $table;
    
        // Service locator injection code
    
        public function getCmsTable()
        {
            // Retrieve the table from the service manager
        }
    
        public function match(Request $request)
        {
            // Match the request on some route field, etc.
        }
    
        public function assemble(array $params = array(), array $options = array())
        {
            // Assemble a URL based on the given parameters (e.g. page ID).
        }
    
        public static function factory($options = array())
        {
            // Construct a new route, based on the options.
        }
    }
    

    You could then register this route as an invokable for the RoutePluginManager in your module configuration:

    'route_manager' => array(
      'invokables' => array(
        'Cms' => 'Application\Router\CmsRoute'
      ),
    ),
    

    Then, you can create a new route (just as you would for any other route) with type Cms. The route plugin manager will create your route instance, and since CmsRoute implements ServiceLocatorAwareInterface, the plugin manager will inject itself in the route. In turn, the plugin manager has the main service manager set, so that you can get the database table from there!

    Of course you can match on page ID, but if you have a hierarchical structure, it's nicer to reflect that in your URLs. I would therefore recommend adding a route field to the database schema and match on that, beginning with the tree root and working down.

提交回复
热议问题