简体   繁体   中英

ZF2: How to get Zend\Db\Adapter inside custom router?

As in title, I'm struggling to access DBAdapter inside Router. Implementing ServiceLocatorAwareInterface isn't much help (ZF2 does not inject anything). Declaring it as a service in module with custom factory is not an option either, as it extends Http/Parts router and requires configuration parameters passed depending on a route (I don't want to hard-code them)

What I've already tried:

module.config.php:

(...)
'router' => array(
    'routes' => array(
        'adm' => array(
            'type'    => 'Custom\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/admin[/:language[/:controller[/:action[/:params]]]]',
                'constraints' => array(
                    'language'  => '(pl|en)',
                    'controller' => "[a-zA-Z0-9_\-]*",
                    'action'     => "[a-zA-Z0-9_\-]*",
                    'params'        => "(.*)",
                ),
                'defaults' => array( ... ),
            ),
            'may_terminate' => true,
        ),
    ),
),
'service_manager' => array(
     (...)
    'invokables' => array(
        'Custom\Mvc\Router\Http\Segment' => 'Custom\Mvc\Router\Http\Segment',
    ),
),
(...)

As of now, Custom\\Mvc\\Router\\Http\\Segment is just a copy of Zend\\Mvc\\Router\\Http\\Segment, with added interfaces ServiceLocatorAwareInterface, AdapterAwareInterface and respective methods in the similar fashion:

public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
    var_dump($serviceLocator);
    exit();
}

It never enters the setServiceLocator method, only RouteInterface::factory(), which then calls constructor.

Setting up a factory didn't help either, again - the code is not executed. Same behavior after moving the 'invocables' or factory to application config.

Currently using Zend Framework 2 RC1

It would have been easier if you would have gisted us som code.. :)

My recommendation would either be to use a factory to instansiate your custom router or set it as an invokable class (Requires you to implement ServiceLocatorAwareInterface so you can set it up in the router)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM