我目前正在尝试为我的捆绑包将一个类依赖注入到另一个类中。我试图以 Symfony2 文档中关于 Newsletter / Mailer 的示例为基础。我目前收到此错误:
Catchable Fatal Error:
Argument 1 passed to Me\MyBundle\Resources\component\SecondClass::__construct()
must be an instance of Me\MyBundle\Resources\component\FirstClass\FirstClass,
none given
MyBundle.php
namespace Me\MyBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Resources\component\FirstClass;
use Resources\component\SecondClass;
class MeMyBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container
->register('first_class', 'FirstClass');
$container
->register('second_class', 'SecondClass')
->addArgument(new Reference('first_class'));
}
}
/Resources/component/FirstClass.php
<?php
namespace Me\MyBundle\Resources\component;
class FirstClass
{
....
}
/Resources/component/SecondClass.php
<?php
namespace Me\MyBundle\Resources\component;
class SecondClass {
private $firstClass;
public function __construct ( FirstClass\FirstClass $firstClass ) {
$this->firstClass = $firstClass;
}
....
关于哪里出错的任何想法?我的印象是 new Reference('first_class') 什么也没传递。我假设,使用上面的方法,不需要向我的 services.yml 添加任何内容
谢谢。
更新:(这是我必须做的,让它工作)
MyBundle.php
$container
->register('first_class', 'Me\MyBundle\Resources\component\FirstClass');
$container
->register('second_class', 'Me\MyBundle\Resources\component\SecondClass')
->addArgument(new Reference('first_class'));
第二类.php
public function __construct ( LanguageCodes $langCodes )
这主要是与名称空间的斗争。
感谢Cerad的耐心,我终于把它整理好了。