最后,经过一番谷歌搜索和实验,我找到了一个完整的解决方案。
只需阅读vendor/bin 中的教义.php。避免硬编码的config-cli.php 文件非常容易。
1。创建实体管理器
在我的例子中,我使用了一个工厂,这种方法为doctrine.em 服务提供了水合物。
($config 特定于我的应用程序,更改值以使用您自己的逻辑。)
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
public function createEntityManager()
{
$config = $this->get('config');
$metadataConfig = Setup::createAnnotationMetadataConfiguration(
[$config->meta('app_path') . '/Entity'],
$config->oc->doctrine->dev_mode
);
return EntityManager::create((array) $config->oc->doctrine->connection, $metadataConfig);
}
2。在 CLI 命令中合并 Doctrine CLI 命令
在您的代码中,例如在某些bootstrap.php 中,您可能会声明您的Symfony\Component\Console\Application 命令行界面,这就是我这样做的方式(foreach 只是添加了在我的services.yml 文件中定义的命令):
$application = new Application('MyApp CLI', '0.0.1');
$services = $container->findTaggedServiceIds('oc.command');
foreach(array_keys($services) as $serviceId)
{
$application->add($container->get($serviceId));
}
$application->run();
现在,我们只需要求 Doctrine 将其命令注入我们的应用程序:
$application = new Application('MyApp CLI', '0.0.1');
$helperSet = ConsoleRunner::createHelperSet($container->get('doctrine.em'));
$application->setHelperSet($helperSet);
ConsoleRunner::addCommands($application);
$services = $container->findTaggedServiceIds('oc.command');
foreach(array_keys($services) as $serviceId)
{
$application->add($container->get($serviceId));
}
$application->run();
就是这样!您也可以使用 arsfeld's answer on this GitHub issue 仅添加 Doctrine 命令的子集。
3。奖励:只导入需要的命令并重命名它们
您可以创建继承 Doctrine 命令的装饰器命令(这对于重新定义 Doctrine 命令的名称很有用,就像 Symfony Doctrine Bundle 所做的那样,例如。orm:validate-schema -> doctrine:schema:validate)。
为此,请删除我们在第 2 步中添加的行 ConsoleRunner::addCommands($application);。对于您要重新定义的每个命令,您需要在您的应用中创建一个注册新命令。此命令将“extends”目标 Doctrine 命令,并将覆盖 configure() 方法。
这是orm:validate-schema 的示例:
<?php
namespace MyApp\Command\Doctrine;
use Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand;
class SchemaValidateCommand extends ValidateSchemaCommand
{
protected function configure()
{
parent::configure();
$this->setName('doctrine:schema:validate');
}
}
某些 Doctrine 命令的别名会污染您的命令命名空间,例如 orm:generate-entities 和 orm:generate:entities。
要删除这些别名,请在 configure() 中添加 ->setAliases(array())。
$this->setName('doctrine:generate:entities')->setAliases([]);
恭喜,你刚刚重做了 Symfony Doctrine Bundle :p (jk)