我很确定您可能会这样做,在他们文档的高级部分中,提到了一种定义文件的方法cli-config.php
。那么是什么阻止你定义这样一个内容如下的文件:
<?php
require 'vendor/autoload.php';
use Doctrine\DBAL\DriverManager;
use Doctrine\Migrations\Configuration\Connection\ExistingConnection;
use Doctrine\Migrations\DependencyFactory;
use Doctrine\Migrations\Configuration\Migration\YamlFile;
// $config = new PhpFile('migrations.php'); // Or use one of the Doctrine\Migrations\Configuration\Configuration\* loaders
$config = new YamlFile('database.yml');
$conn = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]);
return DependencyFactory::fromConnection($config, new ExistingConnection($conn));
所以现在你有一个地方可以$config
在进一步传递之前更改它,但是,为了使它看起来非常干净,我们可以使用装饰器模式来定义我们的配置版本,如下所示:
<?php
class CLIDecorator extends ConfigurationFile
{
/**
* @var YamlFile
*/
private $config;
private $args;
public function __construct(YamlFile $file, $args)
{
$this->config = $file;
$this->args = $args;
}
public function getConfiguration(): Configuration
{
$config = $this->config->getConfiguration();
// I'm not sure if php has a nicer argv parser
// but I'm leaving this up to the reader
if ($this->getMigrationOpts()) {
$config['migrations_paths'] = $this->parse($this->getMigrationOpts());
}
return $config;
}
final protected function parse($rawOpt)
{
$parts = explode("=", $rawOpt);
return str_replace('"', '', $parts[1]);
}
final protected function getMigrationOpts()
{
foreach ($this->args as $arg) {
if (str_starts_with($arg, '--migrations_paths')) {
return $arg;
}
}
return null;
}
}
最后,我们的代码将如下所示:
<?php
$config = new CLIDecorator(new YamlFile('database.yml'), $argv);
$conn = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]);
return DependencyFactory::fromConnection($config, new ExistingConnection($conn));