我目前正在尝试配置我的 Symfony 依赖注入,以便能够使用父服务。按照我在http://symfony.com/doc/current/components/dependency_injection/parentservices.html中找到的描述,我尝试设置以下类作为第一个测试:
邮件程序.php:
namespace testing;
class Mailer
{
private $transport;
public function __construct($transport) {
$this->transport = $transport;
}
public function getTransport() {
return $this->transport;
}
}
邮件管理器.php:
namespace testing;
abstract class MailManager
{
protected $mailer;
public function setMailer(Mailer $mailer)
{
$this->mailer = $mailer;
}
}
通讯管理器.php:
namespace testing;
class NewsletterManager extends MailManager {
function getTransport() {
return $this->mailer->getTransport();
}
}
服务.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,这也不能解决邮件对象的问题没有设置。所以在我看来,建立子类关系也存在问题。
任何帮助,将不胜感激!