9

在使用Symfony 3.3时,我声明了这样的服务:

class TheService implements ContainerAwareInterface
{
    use ContainerAwareTrait;
    ...
}

在我需要 EntityManager 的每个操作中,我从容器中获取它:

$em = $this->container->get('doctrine.orm.entity_manager');

这有点烦人,所以我很好奇 Symfony 是否有类似EntityManagerAwareInterface.

4

3 回答 3

36

传统上,您会在services.yml文件中创建一个新的服务定义,将实体管理器设置为构造函数的参数

app.the_service:
    class: AppBundle\Services\TheService
    arguments: ['@doctrine.orm.entity_manager']

最近,随着 symfony 3.3 的发布,默认的 symfony-standard-edition 将他们的默认services.yml文件更改为默认使用并在to be servicesautowire中添加所有类。AppBundle这消除了添加自定义服务的需要,并且在构造函数中使用类型提示将自动注入正确的服务。

您的服务类将如下所示

use Doctrine\ORM\EntityManagerInterface

class TheService
{
    private $em;

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

    // ...
}

有关自动定义服务依赖项的更多信息,请参阅https://symfony.com/doc/current/service_container/autowiring.html

新的默认services.yml配置文件可在此处获得:https ://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml

于 2017-06-28T18:35:57.927 回答
2

有时我在 services.yml 中将 EM 注入到容器上的服务中,如下所示:

 application.the.service:
      class: path\to\te\Service
      arguments:
        entityManager: '@doctrine.orm.entity_manager'

然后在服务类上获取它的 __construct 方法。希望能帮助到你。

于 2017-06-28T18:18:58.083 回答
0

我遇到了同样的问题并通过编辑迁移代码解决了它。

我换了

$this->addSql('ALTER TABLE user ADD COLUMN name VARCHAR(255) NOT NULL');

经过

$this->addSql('ALTER TABLE user ADD COLUMN name VARCHAR(255) NOT NULL DEFAULT "-"');

我不知道为什么bin/console make:entity在这些情况下不提示我们提供默认值。Django 做到了,而且效果很好。

于 2021-03-14T13:29:40.910 回答