1
votes

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

1
Have you tried using the dependency injection container to build your custom router? You could try that and implement the ServiceLocatorAwareInterfaceJerry Saravia
the word struggling is getting used quite a bit with ZF2thomas-peter
@jerry-saravia - yes, I've tried. The problem is that to use the container, I need access to ServiceManager, and if it were available, there won't be a problem in the first place. Or perhaps I got it wrong? Anyway, a workaround is to create new instance of Di (or directly DbAdapter) using application config file, but it seems like an overkill... Can you probably post sample code if I'm wrong? Thank you in advance.jderda

1 Answers

3
votes

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)