我试图在另一个服务中使用日志记录服务,以便解决该服务的麻烦.
我的config.yml看起来像这样:
services:
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [@security.context]
log_handler:
class: %monolog.handler.stream.class%
arguments: [ %kernel.logs_dir%/%kernel.environment%.jini.log ]
logger:
class: %monolog.logger.class%
arguments: [ jini ]
calls: [ [pushHandler, [@log_handler]] ]
Run Code Online (Sandbox Code Playgroud)
这在控制器等中运行良好.但是当我在其他服务中使用它时,我没有得到任何结果.
有小费吗?
Ino*_*ryy 35
您将服务id作为参数传递给服务的构造函数或setter.
假设您的其他服务是userbundle_service
:
userbundle_service:
class: Main\UserBundle\Controller\UserBundleService
arguments: [@security.context, @logger]
Run Code Online (Sandbox Code Playgroud)
现在Logger被传递给UserBundleService
构造函数,只要你正确地更新它,eG
protected $securityContext;
protected $logger;
public function __construct(SecurityContextInterface $securityContext, Logger $logger)
{
$this->securityContext = $securityContext;
$this->logger = $logger;
}
Run Code Online (Sandbox Code Playgroud)
您可以将服务直接注入到另一个服务中(例如MainService
)
// AppBundle/Services/MainService.php
// 'serviceName' is the service we want to inject
public function __construct(\AppBundle\Services\serviceName $injectedService) {
$this->injectedService = $injectedService;
}
Run Code Online (Sandbox Code Playgroud)
然后,只需在MainService的任何方法中使用注入的服务即可:
// AppBundle/Services/MainService.php
public function mainServiceMethod() {
$this->injectedService->doSomething();
}
Run Code Online (Sandbox Code Playgroud)
和中提琴!您可以访问注入服务的任何功能!
// services.yml
services:
\AppBundle\Services\MainService:
arguments: ['@injectedService']
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24076 次 |
最近记录: |