为什么symfony容器有服务重复?

时间:2018-04-12 10:25:47

标签: php symfony symfony4

我想将课程App\Service\SomeService注册为服务。

这是我的services.yaml

services:
    _defaults:
        autowire: false
        autoconfigure: true
        public: true
    App\:
        resource: '../src/*'
        exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']
    someservice:
        class: App\Service\SomeService

现在我运行debug:container someservice

Information for Service "someservice"
=====================================

 ---------------- ------------------------- 
  Option           Value                    
 ---------------- ------------------------- 
  Service ID       someservice              
  Class            App\Service\SomeService  
  Tags             -                        
  Public           yes                      
  Synthetic        no                       
  Lazy             no                       
  Shared           yes                      
  Abstract         no                       
  Autowired        no                       
  Autoconfigured   yes                      
 ---------------- ------------------------- 

但是,当我运行debug:container App\\Service\\SomeService时:

Information for Service "App\Service\SomeService"
=================================================

 ---------------- ------------------------- 
  Option           Value                    
 ---------------- ------------------------- 
  Service ID       App\Service\SomeService  
  Class            App\Service\SomeService  
  Tags             -                        
  Public           yes                      
  Synthetic        no                       
  Lazy             no                       
  Shared           yes                      
  Abstract         no                       
  Autowired        no                       
  Autoconfigured   yes                      
 ---------------- ------------------------- 

事实证明我有另一个服务指向同一个类:

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Service\SomeService;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     * @return Response
     */
    public function index()
    {
        var_dump($this->get('someservice') === $this->get(SomeService::class));
        return new Response;
    }
}

输出:

  

布尔(假)

为什么我注册了两个服务而不是一个?

1 个答案:

答案 0 :(得分:4)

那是因为您在services.yaml中注册了两次。

自动使用此行:

App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

另一个,手动:

someservice:
    class: App\Service\SomeService

由于它们的名称不同(someserviceApp\Service\SomeService),因此它们与Symfony不同。

我建议您删除第二个声明,并仅在控制器中使用其完全限定名称调用该服务:$this->get(SomeService::class)