如何向Symfony服务添加构造函数参数

问题描述:

我创建了一个使用FilesystemCache的服务,我不想在每次调用服务时创建一个新的FilesystemCache,所以我在服务构造函数中有一个参数,我可以给出给出一个实例。 我到目前为止有:如何向Symfony服务添加构造函数参数

服务类

class MyService 
{ 

    private $cache; 

    private $url; 

    /** 
    * MyService constructor. 
    * @param FilesystemCache $cache 
    */ 
    public function __construct(FilesystemCache $cache) 
    { 
     $this->cache = $cache; 
    } 

    private function data() 
    { 
     if ($this->cache->has('data')) { 
      $data = $this->cache->get('data'); 
     } else { 
      $data = file_get_contents("my/url/to/data"); 
     } 

     return $data; 
    } 
} 

配置

services: 
    # Aliases 
    Symfony\Component\Cache\Adapter\FilesystemAdapter: '@cache.adapter.filesystem' 

    # Services 
    services.myservice: 
    class: AppBundle\Services\MyService 
    arguments: 
     - '@cache.adapter.filesystem' 

当我使用该服务:

$myService = $this->container->get('services.myservice'); 

但我得到的是一个错误:

The definition "services.myservice" has a reference to an abstract definition "cache.adapter.filesystem". Abstract definitions cannot be the target of references. 

所以,我的问题是我怎么也得修改我的服务或我的声明,或什么的,能够做我想做的事:不创建一个实例每次我打电话时间服务。

+0

我希望你的论点是:'Symfony \ Component \ Cache \ Adapter \ FilesystemAdapter'不是别名服务'@ cache.adapter.filesystem'。这可能吗? – dbrumann

+0

那么据我看你应该做一个新的FilesystemCache,因为它是一个抽象类,除非你扩展这个类然后在构造函数中使用子类 –

+0

@dbrumann如果我用路由替换别名我有下一个错误:''依赖于不存在的服务“\ Symfony \ Component \ Cache \ Adapter \ FilesystemAdapter”。# – piterio

为了做到这一点,我必须在我的服务构造函数中使用我想用的类来注册一个新的服务。所以,我的services.yml会像:

services: 
    filesystem.cache: 
    class: Symfony\Component\Cache\Simple\FilesystemCache 
    services.myservice: 
    class: AppBundle\Services\MyService 
    arguments: 
     - '@filesystem.cache' 

,现在我能够用我的服务没有得到一个错误。

+0

而不是定义filesystem.cache,只需用类名替换@ filesystem.cache即可。我认为autowire会把它拿起来。 – Cerad

+0

@Cerad我得到:'类型错误:传递给AppBundle \ Services \ MyService :: __ construct()的参数1必须是Symfony \ Component \ Cache \ Simple \ FilesystemCache的一个实例,字符串给出' – piterio

我强烈建议您使用cache.app服务,而不是您自己的filesystem.cache。此外,你可以创建自己的适配器。

+0

如果我将@filesystem .cache with @ cache.app我得到的是这样的错误:类型错误:传递给AppBundle \ Services \ MyService :: __ construct()的参数1必须是Symfony \ Component \ Cache \ Simple \ FilesystemCache的一个实例,Symfony的实例\ Component \ Cache \ Adapter \ TraceableAdapter given' – piterio

使用标准S3.3自动装配的设置,这个工作对我来说:

// services.yml 

// This basically gives autowire a concrete cache implementation 
// No additional parameters are needed 
Symfony\Component\Cache\Simple\FilesystemCache: 

// And there is no need for any entry for MyService 

....

// MyService.php 
use Psr\SimpleCache\CacheInterface; 

public function __construct(CacheInterface $cache) 

这当然如果你只有一个具体实施只会工作您的容器中的CacheInterface。