使 Doctrine 迁移遵循 ContainerAwareInterface



>我有一个教义迁移,看起来像这样:

<?php
namespace ApplicationMigrations;
use DoctrineORMMappingPushNotification;
use DoctrineDBALMigrationsAbstractMigration;
use SymfonyComponentDependencyInjectionContainerAwareInterface;
use DoctrineDBALSchemaSchema;
/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20180123103147 extends AbstractMigration implements ContainerAwareInterface
{
    private $container;
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        $em = $this->container->getDoctrine()->getManager();
        $tableName = $em->getClassMetadata('AppBundle:PushNotification')->getTableName();
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on 'mysql'.');
        $this->addSql('ALTER TABLE '.$tableName.' ADD COLUMN   last_offset int(11) ');
        $this->addSql('ALTER TABLE '.$tableName.' ADD COLUMN   failure_count int(11) ');
        $this->addSql('ALTER TABLE '.$tableName.' ADD COLUMN   is_sent int(11) ');
        $this->addSql('ALTER TABLE '.$tableName.' ADD COLUMN   send_date datetime ');

    }
    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        $em = $this->container->getDoctrine()->getManager();
        $tableName = $em->getClassMetadata('AppBundle:PushNotification')->getTableName();
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on 'mysql'.');
        $this->addSql('ALTER TABLE '.$tableName.' DROP COLUMN   last_offset ');
        $this->addSql('ALTER TABLE '.$tableName.' DROP COLUMN   failure_count ');
        $this->addSql('ALTER TABLE '.$tableName.' DROP COLUMN   is_sent ');
        $this->addSql('ALTER TABLE '.$tableName.' DROP COLUMN   send_date ');
    }
}

。运行迁移时,我收到一条错误消息,指出Declaration of ApplicationMigrationsVersion20180123103147::setContainer() must be compatible with SymfonyComponentDependencyInjectionContainerAwareInterface::setContainer(SymfonyComponentDependencyInjectionContainerInterface $container = NULL)

此错误似乎不合适,因为我直接从相关接口复制了方法签名。

我在这里缺少一些明显的代码吗?

您似乎正在尝试将container注入另一个服务,通常强烈建议不要这样做。相反,您可以注入EntityManagerInterface并使用它。

但是,我确实看到这是一个迁移文件。在给定的代码中没有理由为什么应该在这里,而只是像这样硬编码表名:

$this->addSql('ALTER TABLE push_notification ADD COLUMN  last_offset int(11)');
因此,总而言之,您

收到该错误的原因是迁移期望将容器的实例传递给您的迁移,但是,由于您未将迁移注册为服务,因此从未发生这种情况。

(sidenote: never register a migration as a service)

我认为您错误的原因只是因为您没有放入使用部分

use SymfonyComponentDependencyInjectionContainerInterface;

事实上,它与没有使用的接口不是同一个原型(不引用 ContainerInterface 的同一类(

尽管如此,前面回答的评论也很严谨!

相关内容

  • 没有找到相关文章