Configuring class alias for using with Zend\Di\Di

2019-08-14 05:53发布

I have a logger class (Application\Debug\Logger) for logging various debug messages from whole application to log files. And I would like to get instance of that class using simple alias 'logger'. So I try to configure Zend\Di\Di, so that I could do something like this in, for example, module controller or another application components:

$di = new \Zend\Di\Di();
$logger = $di->get('logger');
//$logger should be Application\Debug\Logger instance...

To achieve this, I have this in Application/config/module.config.php:

'di' => array(
    'instance' => array(
        'alias' => array(
            'logger' => 'Application\Debug\Logger',
        ),
    ),
)

But the problem is: alias 'logger' doesn`t work. I can use Di and get class by full name (Application\Debug\Logger), but not by alias (I get error: Class logger could not be located in provided definitions). I suppose that I have to pass the configuration to Di somehow, but I don't know how. Can you help me?

1条回答
迷人小祖宗
2楼-- · 2019-08-14 06:34

I`ve found partial solution of my problem. I noticed that when I call ServiceManager, it uses also Dependency Injection configuration to find proper class, so I can call:

$logger = $this->getServiceLocator()->get('logger');

in the controller to get logger instance by alias configured for DI.

So in my config file I could also put:

'service_manager' => array(
    'invokables' => array(
        'logger' => 'Application\Debug\Logger',
    )
), 

and it works the same as previous di config example. But I still don`t fully understand how I can properly use DI, so I would be grateful if someone could explain it to me.

查看更多
登录 后发表回答