2017-08-16 98 views
0

我創建了一個使用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

回答

0

爲了做到這一點,我必須在我的服務構造函數中使用我想用的類來註冊一個新的服務。所以,我的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

1

我強烈建議您使用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

0

使用標準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。