簡體   English   中英

在 Symfony 2.8 中將服務注入 controller?

[英]Inject service into controller in Symfony 2.8?

我真的很難嘗試將服務注入 controller,我發現了一些帖子,這就是我嘗試過的:

我有一個名為 FormatService 的服務

services:
    formats_service:
            class: FormatsBundle\Services\FormatService

我希望將它注入FormatsController所以我嘗試將控制器定義為服務,然后按照文檔狀態更改我的整個路由

app.formats_controller:
        class: ABundle\Controller\FormatsController
        arguments: ["@formats_service"]

這樣做會給我一個Error: Call to a member function has() on null

然后我嘗試從容器中收集它,做這樣的事情

public function __construct () {
  $this->formatService = $this->container->get('formats_service');
}

這給了我一個錯誤, $this->container似乎是 null。

我做了一項研究,發現這篇文章INJECT the container to my controller 但解決方案與我從一開始就無法完成的事情相同,我無法注入服務,因為這樣做我需要將我的 controller 定義為服務但做所以給了我Error: Call to a member function has() on null每當我嘗試從我的 controller

有沒有辦法將服務注入 controller 而不會在 Symfony 2.8 中搞得一團糟?

將 controller 定義為服務時,您必須直接注入服務而不訪問容器。 當您的 controller 擴展 Symfony 的基礎 controller 時,您可以采用混合方法,但通常不鼓勵這樣做。

如果您修改控制器的構造函數,它應該可以工作:

public function __construct(FormatsBundle\Services\FormatService $formatService) 
{
    $this->formatService = $formatService;
}

編輯:如果你想在你的 controller 中使用容器,你應該擴展Symfony\Bundle\FrameworkBundle\Controller\Controller或添加use Symfony\Component\DependencyInjection\ContainerAwareTrait ,但是在將控制器用作服務時也不鼓勵兩者,因為那時你也可以寫一個普通的 controller。

當您使用 controller 時,您無需將其聲明為服務,因為controller具有您可以使用的容器

public function newAction()

{

// the container will instantiate a new FormatService()
$myService = $this->container->get('formats_service');

}

你可以在這里看到更多https://symfony.com/doc/2.8/service_container.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM