带前缀的 Symfony 学说(迁移)

Symfony Doctrine (Migration) with prefix

我们的应用程序需要一个 table 前缀名称。我希望我们不需要它,但用户就是用户。 目前我们有这个 TablePrefix Subscriber

class TablePrefixSubscriber implements \Doctrine\Common\EventSubscriber {
protected $prefix = '';
public function __construct($prefix = '') {
    $this->prefix = (string) $prefix;
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) {
    $classMetadata = $eventArgs->getClassMetadata();
    if(strlen($this->prefix)) {
        if(0 !== strpos($classMetadata->getTableName(), $this->prefix)) {
            $classMetadata->setTableName($this->prefix . $classMetadata->getTableName());
        }
    }
    foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
        if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY) {
            if(!isset($classMetadata->associationMappings[$fieldName]['joinTable'])) { continue; }
            $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
            if(0 !== strpos($mappedTableName, $this->prefix)) {
                $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
            }
        }
    }
}
public function getSubscribedEvents() {
    return array('loadClassMetadata');
}

服务配置:

services:
app.event.doctrine.table_prefix_subscriber:
class: RYZ\Bundle\CoreBundle\EventListener\TablePrefixSubscriber
arguments: ['%database_prefix%']
tags:
  - { name: doctrine.event_subscriber }

如果您没有迁移或没有手动编写查询(通过使用查询构建器),这就很好用。

我不知道如何将前缀添加到学说迁移中的查询。

如果我可以在迁移中访问前缀配置变量 database_prefix 并将其添加到每个查询中就好了。

我还想访问实体存储库中的变量 类。

如果有人能指出正确的方向,我会很高兴。

更新:我听说过 Doctrine Naming Strategy,但我认为这对我没有帮助? (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/namingstrategy.html)

好的,我想我找到了迁移的解决方案: 关键字:ContainerAwareInterface

您可以将 ContainerAwareInterface 实施到您的迁移 class 并且只访问您实施的所有参数和服务。太棒了!

这是一个例子:

<?php

namespace FooBla\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class Version20160810121166 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->getParameter('database_prefix'); //Just use the parameter directly in the migration calls
    $this->addSql('CREATE TABLE `'.$em.'sessions` (`sess_id` VARBINARY(128) NOT NULL PRIMARY KEY, `sess_data` BLOB NOT NULL, `sess_time` INTEGER UNSIGNED NOT NULL, `sess_lifetime` MEDIUMINT NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB');
}

/**
 * @param Schema $schema
 */
public function down(Schema $schema)
{
}
}