【问题标题】:Symfony2. Force a service to get instancedSymfony2。强制服务实例化
【发布时间】:2016-03-22 20:29:07
【问题描述】:

我正在使用 symfony 2.8,我遇到了一个服务必须被实例化的情况,即使某处没有请求它。

为什么?因为这个核心服务配置了通过方法调用传输到核心的标记服务(我在编译器过程中这样做了)。 然后,如果我在没有请求 Core 的情况下请求这些标记服务之一,它将不会被配置然后无法使用。

这是编译器传递:

$coreDefinition = $container->findDefinition(
    'app.improvements.core'
);

$taggedAppliers = $container->findTaggedServiceIds('app.improvement.applier');

foreach ($taggedAppliers as $id => $tags) {
    $coreDefinition->addMethodCall(
        'registerApplier',
        [new Reference($id)]
    );
}

$taggedImprovements = $container->findTaggedServiceIds(
    'app.improvement'
);

// Only method found to initialize improvements.
foreach ($taggedImprovements as $id => $tags) {
    $coreDefinition->addMethodCall(
        'registerImprovement',
        [new Reference($id)]
    );
}

综上所述,Appliers 注册了 Improvement,Core 注册了 Appliers。核心将改进与应用程序相关联,因为每个改进都必须在核心存储的特定应用程序中注册。

问题是,当我只请求一个 Applier 时,它的改进没有注册到其中,因为核心没有实例化。

谢谢。

【问题讨论】:

  • 服务可以做成单例吗?如果是这样,您可以通过内核事件对其进行实例化,并对其进行适当配置,以便稍后被任何其他对象调用。

标签: php symfony containers


【解决方案1】:

抛开设计问题不谈,实例化服务的最简单方法是使用an event listener。在您的情况下,您将监听 kernel.request 并从容器中提取您的服务。

class RequestListener
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        $event->getKernel()->getContainer()->get('service_id');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    相关资源
    最近更新 更多