2017-02-24 5 views
0

DiTest名前空間の下にいくつかのサンプルクラスがあります。symfony/dependency-injectionでオートワイヤリングを動作させるにはどうすればよいですか?

namespace DiTest; 

class Transport 
{ 
    public function send($mail) 
    { 
     echo $mail . PHP_EOL; 
     echo 'Mail Sent'; 
    } 
} 

class Mailer 
{ 
    protected $transport; 

    public function __construct(Transport $transport) 
    { 
     $this->transport = $transport; 
    } 

    public function send($mail) 
    { 
     if ($this->transport) { 
      $this->transport->send($mail); 
     } else { 
      echo 'No transport set!' . PHP_EOL; 
     } 
    } 
} 

次に、このyaml設定ファイルがあります。

services: 
    transport: 
     class: DiTest\Transport 
    mailer: 
     class: DiTest\Mailer 
     autowire: true 

最後に、私はindex.phpの

use Symfony\Component\DependencyInjection\ContainerBuilder; 
use Symfony\Component\Config\FileLocator; 
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; 

require_once __DIR__.'/vendor/autoload.php'; 

$container = new ContainerBuilder(); 
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '\src')); 
$loader->load('services.yml'); 

$mailer = $container->get('mailer'); 
$mailer->send('Hello world!'); 

でこれを持っていることは、コンストラクタの引数に渡さずメーラーのクラスをインスタンス化しようとします。誰が私が間違っているのか教えてもらえますか?

オートワイヤリングの問題をどのようにデバッグする必要がありますか?

+2

私は最後の質問に答えることができます:autowireを使用しないでautowireをデバッグします。あなたはS2.8を使っていますか? – Cerad

+0

私はautowireをラピッドプロトタイピングに使うべきだと思います。私はdependency-injection、config、yamlだけを使用しています。それらはすべてバージョン3.2です。 symfonyの二重コンテナがどのように動作するかを見てみただけです。 – srayner

答えて

0

すべてのautowired参照が解決されるようにメーラーサービスを取得する前に、$container->compile();に電話する必要があります。

関連する問題