问题描述
我有一个记录器类(Application\Debug\Logger),用于将各种调试消息从整个应用程序记录到日志文件中。
而且我想使用简单的别名 logger来获取该类的实例。
因此,我尝试配置Zend\Di\Di,以便可以在模块控制器或其他应用程序组件中执行类似的操作:
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...
为此,我在Application / config / module.config.php中具有以下内容:
To achieve this, I have this in Application/config/module.config.php:
'di' => array(
'instance' => array(
'alias' => array(
'logger' => 'Application\Debug\Logger',
),
),
)
但问题是:别名'logger不起作用。我可以使用Di并通过全名(Application\Debug\Logger)获取类,但不能通过别名获取(我得到错误:在提供的定义中找不到类记录器)。我想我必须以某种方式将配置传递给Di,但我不知道如何。您能帮我吗?
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?
推荐答案
我已经找到了部分解决方案来解决我的问题。我注意到,当我调用ServiceManager时,它也使用依赖注入配置来查找正确的类,因此我可以调用:
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');
在控制器中通过为DI配置的别名获取记录器实例。
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',
)
),
,它的工作原理与前面的di config示例相同。
但是我仍然不完全了解如何正确使用DI,因此,如果有人可以向我解释它,我将不胜感激。
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.
这篇关于配置类别名以与Zend\Di\Di一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!