在我的 Symfony 2.8
项目中,我使用包继承来覆盖/扩展 FOSUserBundle
:自定义包中具有相同路径和名称的文件会覆盖FOSUserBundle
。
虽然这适用于 Controller 和资源(如翻译和 View ),但它似乎不适用于服务类。
例如 FOSUserBundle
使用 Resources\config\util.xml
来定义 fos_user.util.password_updater
服务来使用定义的类在 Util\PasswordUpdater.php
中。
简单地将 Util\PasswordUpdater.php
添加到继承的包中是行不通的。此文件将被忽略, bundle 仍使用原始版本。
这是服务的缩进行为(因为原始服务定义仍然指向原始文件),还是我做错了什么?
覆盖/扩展服务的正确方法是什么?我找到了 information , 使用 compiler pass
通常是最好的解决方案。但是,当已经使用包继承时,这也是真的吗?
最佳答案
要覆盖服务,您需要在 Bundle 中创建一个 CompilerPass:
<?php
namespace AppBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Class OverrideServiceCompilerPass
* @package Shopmacher\IsaBodyWearBundle\DependencyInjection\Compiler
*/
class OverrideServiceCompilerPass implements CompilerPassInterface
{
/**
* Overwrite project specific services
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$defNewService = $container->getDefinition('service.id.you.want.to.override');
$defNewService ->setClass('AppBundle\Service\NewService');
}
}
将其注册到您的 Bundle 文件中:
class AppBundle extends FOSUserBundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new OverrideServiceCompilerPass());
}
}
然后您的服务文件将被加载。在此文件中,您可以扩展原始服务文件和共享方法,也可以创建全新的服务。
关于php - Symfony 包继承 - 如何覆盖/扩展服务类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40991378/