使用父服务的Symfony2依赖注入不起作用

时间:2012-07-10 14:50:37

标签: php symfony dependency-injection

我正在尝试配置我的Symfony依赖注入,以便我能够使用父服务。按照我在http://symfony.com/doc/current/components/dependency_injection/parentservices.html中找到的描述,我尝试将以下类设置为第一个测试:

Mailer.php:

namespace testing;

class Mailer
{
    private $transport;

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

    public function getTransport() {
        return $this->transport;
    }
}

MailManager.php:

namespace testing;

abstract class MailManager
{
    protected $mailer;

    public function setMailer(Mailer $mailer)
    {
         $this->mailer = $mailer;
    }
}

NewsletterManager.php:

namespace testing;

class NewsletterManager extends MailManager {
    function getTransport() {
        return $this->mailer->getTransport();
    }
}

services.yml:

 parameters:
    mailer.transport: sendmail

services:
    mailer:
        class:     testing\Mailer
        arguments: [%mailer.transport%]
    mail_manager:
        class:     testing\MailManager
        abstract:  true
        calls:
             - [ setMailer, [ @mailer ] ]
    newsletter_manager:
        class:     testing\NewsletterManager
        parent:    mail_manager

但是当我尝试使用以下代码运行此配置时:

require_once 'ClassLoading.php';
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;

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

$nm = $container->get('newsletter_manager');
echo $nm->getTransport();

我总是收到这个错误:

PHP Fatal error:  Call to a member function getTransport() on a non-object in C:\IGMI\workspace\TryingHard\loading\NewsletterManager.php on line 7

有一件事似乎是从不调用抽象类的setter,但是即使我使抽象类具体化并从实际调用setter的容器中检索它,这也无法解决问题。邮件程序对象未设置。所以它告诉我,建立子类关系也存在问题。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

你应该在尝试访问服务之前编译容器构建器我认为...... 所以看起来应该是这样的:

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

use Symfony\Component\DependencyInjection\ContainerBuilder;

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

$container->compile(); //add this line

$nm = $container->get('newsletter_manager');
echo $nm->getTransport();