2017-09-24 16 views
0

您好我想注入一個服務類而不呼叫她的構造函數,是我還沒有傳遞給此注入的構造函數類的參數。Symfony注入服務類沒有打電話給她的構造函數

例:

services: 
your.service.name: 
    class: AppBundle\Services\YourClassName 
    arguments: ['@doctrine.services.paginator'] 

doctrine.services.paginator: 
    class: Doctrine\ORM\Tools\Pagination\Paginator 
    public: false 

返回錯誤

Type error: Too few arguments to function Doctrine\ORM\Tools\Pagination\Paginator::__construct(), 0 passed in ... and at least 1 expected

+1

爲什麼要在不調用構造函數的情況下注入'Paginator'?我有一種感覺,你試圖去錯誤的方式。 – qooplmao

+0

我可以在服務內做「新Paginator()」嗎? – spinoza

回答

1

這是一個有點難以實例化一個類,而無需使用構造函數,
PHP文件說:

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

PHP constructor documentation

如果你想使用分頁程序沒有注入依賴,你可以遵循教義文檔:

Doctrine paginator documentation

基本上,你在你的倉庫中插入使用的語句。

use Doctrine\ORM\Tools\Pagination\Paginator; 

然後使用分頁程序類的對象與查詢:

$qb = $this->CreateQueryBuilder('u'); 
// ... build your query here... 
$qb->getQuery(); 
$paginator = new Paginator($qb, false); 
$count = count($paginator); 
return array($paginator, $count); // Process the results in your controller 

希望這有助於

1

您可以使用setter注入,這是可選的,並不推薦使用,但我對此不會深究。

例子:

services: 
    your.service.name: 
     class: AppBundle\Services\YourClassName 

,而是在運行時注入它:

$this->get('your.service.name')->setPaginator($paginator); 

如果

<?php 

class YourClassName 
{ 
    private $paginator; 

    public function setPaginator(PaginatorInterface $paginator) 
    { 
     $this->paginator = $paginator; 
    } 

    public function getPaginator() 
    { 
     if ($this->paginator instanceof PaginatorInterface) { 
      return $this->paginator; 
     } 

     throw new \RuntimeException('Paginator is not defined'); 
    } 
} 

然後你就可以在不指定分頁程序作爲參數注入你的服務,如果您還需要在容器中注入標籤,則可以使用calls argum與服務,more in docs

如果您需要在每次從容器獲得服務時獲取新實例,則可以使用shared參數more in docs