我真的很努力嘗試將服務注入控制器,我找到了一些帖子,這就是我嘗試過的:我有一個名為 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似乎是空的。我無法注入服務,因為要做到這一點,我需要將我的控制器定義為服務,但這樣做所以Error: Call to a member function has() on null每當我嘗試從控制器訪問任何端點時都會給我有沒有什么方法可以將服務注入到控制器中,而不用在 Symfony 2.8 中搞得一團糟?
2 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
將控制器定義為服務時,您必須直接注入服務而無需訪問容器。當你的控制器擴展 Symfony 的基本控制器時,你可以采用混合方法,但通常不鼓勵這樣做。
如果您修改控制器的構造函數,它應該可以工作:
public function __construct(FormatsBundle\Services\FormatService $formatService) { $this->formatService = $formatService; }
編輯:如果您想在控制器中使用容器,您應該擴展Symfony\Bundle\FrameworkBundle\Controller\Controller
或添加use Symfony\Component\DependencyInjection\ContainerAwareTrait
,但在使用控制器作為服務時,不鼓勵兩者,因為這樣您也可以編寫常規控制器。

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
當您使用控制器時,您不需要將其聲明為服務,因為控制器具有容器,您可以使用?php app/console debug:container來查看您的服務是否在容器中,并且可以直接在操作中使用它
public?function?newAction()
{
//?the?container?will?instantiate?a?new?FormatService() $myService?=?$this->container->get('formats_service');
}
- 2 回答
- 0 關注
- 153 瀏覽
添加回答
舉報
0/150
提交
取消