doucuo8618 2015-12-26 18:00
浏览 59
已采纳

Symfony2是否检测到服务之间的周期性依赖性?

Say you need to build a complex service relying on other services in Symfony2. One way to create these services is to create factories.

Yet, is it possible to create services with cyclical dependencies to other services in Symfony2 or not? I know this is not a good coding practice, but that is not my question.

Should one implement service setter methods as mentioned in the documentation to enable this? Else, how does Symfony2 deals with these chicken and egg issues? Does it throw an error?

  • 写回答

1条回答 默认 最新

  • douju7765 2015-12-28 13:27
    关注

    The best way to find out is to try it:

    1). Install a Symfony standard edition application

    I installed Symfony 2.8.1 for this example.

    2). In the default AppBundle add the following files in Services folder:

    ServiceA.php:

    namespace AppBundle\Services;
    
    class ServiceA
    {
        private $service;
    
        public function __construct(ServiceB $service)
        {
            $this->service = $service;
        }
    }
    

    ServiceB.php:

    namespace AppBundle\Services;
    
    class ServiceB
    {
        private $service;
    
        public function __construct(ServiceA $service)
        {
            $this->service = $service;
        }
    }
    

    3). Add an extension subclass in DependencyInjection folder:

    AppExtension.php:

    namespace AppBundle\DependencyInjection;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\Config\FileLocator;
    use Symfony\Component\DependencyInjection\Extension\Extension;
    use Symfony\Component\DependencyInjection\Loader;
    
    class AppExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
            $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources'));
            $loader->load('services.yml');
        }
    }
    

    4). And declare the circular-dependent services in Resources folder:

    services.yml:

    services:
        service_a:
            class: AppBundle\Services\ServiceA
            arguments:
                - @service_b
    
        service_b:
            class: AppBundle\Services\ServiceB
            arguments:
                - @service_a
    

    After all this, if you run php app/console --version, you will get the following error:

    [Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException]
    Circular reference detected for service "service_a", path: "service_a -> service_b -> service_a".
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题