2017-10-18 108 views
0

我想有SwiftMailer服務於一體的動作使用以下技術提供給我:Symfony的服務注入到行動

http://symfony.com/doc/current/service_container.html#fetching-and-using-services

public function submitAction (Request $request, \Swift_Mailer $mailer) 
{ 
     $mailer = $this->get('mailer'); 
     var_dump($mailer); 
} 

這是錯誤:

Controller "AppBundle\Controller\QuoteController::submitAction()" requires that you provide a value for the "$mailer" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

var_dump告訴我這不是空的 - 我最近升級到Symfony 3.3.10並將我的services.yml更改爲以下內容:

services: 
    _defaults: 
    autowire: true 
    autoconfigure: true 
    public: true 

回答

2

服務通常(並且可以自動)注入到構造函數中。

它們也可以被自動地放入動作方法的參數,但[控制器必須進行標記,使其能夠]。(http://symfony.com/doc/current/service_container/3.3-di-changes.html

# controllers are imported separately to make sure they're public 
# and have a tag that allows actions to type-hint services 
AppBundle\Controller\: 
    resource: '../../src/AppBundle/Controller' 
    tags: ['controller.service_arguments'] 

的請求(和自3.2+,SessionInterface和用戶/ UserInterface等)通過內置的PHP反射api進行檢測。除了現有的ParameterConverter(用於從參數ID獲取操作方法參數的實體)之外,還有一個更專用的子系統可以識別並自動將它們添加到ArgumentResolver(使用SessionValueResolverServiceValueResolver)。

+0

我想知道這是否是它。不過,我很好奇,如果控制器未被標記,請求如何被注入?我會馬上嘗試,並接受你的答案,如果它的工作 - 謝謝:) –

+0

只是爲了信息,請求對象一直作爲一種特殊情況處理,並沒有直接關係到新的動作注入功能。請求有點獨特,因爲Symfony支持嵌套請求,並且動作接收當前請求很重要。 – Cerad