More work to DoctrineBundle Console Commands and updated README

This commit is contained in:
Jonathan H. Wage 2010-04-14 21:07:58 -04:00 committed by Fabien Potencier
parent 4db2caebae
commit 2c41e93248
21 changed files with 609 additions and 231 deletions

View File

@ -29,8 +29,21 @@ class ClearMetadataCacheDoctrineCommand extends MetadataCommand
protected function configure()
{
parent::configure();
$this->setName('doctrine:clear-cache:metadata');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to clear the cache for.');
$this
->setName('doctrine:cache:clear-metadata')
->setDescription('Clear all metadata cache for a entity manager.')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to clear the cache for.')
->setHelp(<<<EOT
The <info>doctrine:cache:clear-metadata</info> command clears all metadata cache for the default entity manager:
<info>./symfony doctrine:cache:clear-metadata</info>
You can also optionally specify the <comment>--em</comment> option to specify which entity manager to clear the cache for:
<info>./symfony doctrine:cache:clear-metadata --em=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)

View File

@ -29,8 +29,21 @@ class ClearQueryCacheDoctrineCommand extends QueryCommand
protected function configure()
{
parent::configure();
$this->setName('doctrine:clear-cache:query');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to clear the cache for.');
$this
->setName('doctrine:cache:clear-query')
->setDescription('Clear all query cache for a entity manager.')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to clear the cache for.')
->setHelp(<<<EOT
The <info>doctrine:cache:clear-query</info> command clears all query cache for the default entity manager:
<info>./symfony doctrine:cache:clear-query</info>
You can also optionally specify the <comment>--em</comment> option to specify which entity manager to clear the cache for:
<info>./symfony doctrine:cache:clear-query --em=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)

View File

@ -29,8 +29,33 @@ class ClearResultCacheDoctrineCommand extends ResultCommand
protected function configure()
{
parent::configure();
$this->setName('doctrine:clear-cache:result');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to clear the cache for.');
$this
->setName('doctrine:cache:clear-result')
->setDescription('Clear result cache for a entity manager.')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to clear the cache for.')
->setHelp(<<<EOT
The <info>doctrine:cache:clear-result</info> command clears all result cache for the default entity manager:
<info>./symfony doctrine:cache:clear-result</info>
You can also optionally specify the <comment>--em</comment> option to specify which entity manager to clear the cache for:
<info>./symfony doctrine:cache:clear-result --em=default</info>
If you don't want to clear all result cache you can specify some additional options to control what cache is deleted:
<info>./symfony doctrine:cache:clear-result --id=cache_key</info>
Or you can specify a <comment>--regex</comment> to delete cache entries that match it:
<info>./symfony doctrine:cache:clear-result --regex="user_(.*)"</info>
You can also specify a <comment>--prefix</comment> or <comment>--suffix</comment> to delete cache entries for:
<info>./symfony doctrine:cache:clear-result --prefix="user_" --suffix="_frontend"</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)

View File

@ -0,0 +1,124 @@
<?php
namespace Symfony\Framework\DoctrineBundle\Command;
use Symfony\Components\Console\Input\InputArgument;
use Symfony\Components\Console\Input\InputOption;
use Symfony\Components\Console\Input\InputInterface;
use Symfony\Components\Console\Output\OutputInterface;
use Symfony\Components\Console\Output\Output;
use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Doctrine\ORM\Mapping\Driver\DatabaseDriver;
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
use Doctrine\ORM\Tools\ConvertDoctrine1Schema;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* Convert a Doctrine 1 schema to Doctrine 2 mapping files
*
* @package Symfony
* @subpackage Framework_DoctrineBundle
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class ConvertDoctrine1SchemaDoctrineCommand extends DoctrineCommand
{
protected function configure()
{
$this
->setName('doctrine:mapping:convert-d1-schema')
->setDescription('Convert a Doctrine 1 schema to Doctrine 2 mapping files.')
->addArgument('d1-schema', InputArgument::REQUIRED, 'Path to the Doctrine 1 schema files.')
->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to write the converted mapping information to.')
->addArgument('mapping-type', InputArgument::OPTIONAL, 'The mapping type to export the converted mapping information to.')
->setHelp(<<<EOT
The <info>doctrine:mapping:convert-d1-schema</info> command converts a Doctrine 1 schema to Doctrine 2 mapping files:
<info>./symfony doctrine:mapping:convert-d1-schema /path/to/doctrine1schema "Bundle\MyBundle" xml</info>
Each Doctrine 1 model will have its own XML mapping file located in <info>Bundle/MyBundle/config/doctrine/metadata</info>.
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$bundleClass = null;
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
foreach ($this->container->getKernelService()->getBundles() as $bundle)
{
if (strpos(get_class($bundle), $input->getArgument('bundle')) !== false)
{
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
if (isset($bundleDirs[$namespace]))
{
$destPath = realpath($bundleDirs[$namespace]).'/'.$class;
$bundleClass = $class;
break;
}
}
}
$type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
if ($type === 'annotation')
{
$destPath .= '/Entities';
}
else
{
$destPath .= '/Resources/config/doctrine/metadata';
}
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter($type);
if ($type === 'annotation')
{
$entityGenerator = $this->getEntityGenerator();
$exporter->setEntityGenerator($entityGenerator);
}
$converter = new ConvertDoctrine1Schema($input->getArgument('d1-schema'));
$metadata = $converter->getMetadata();
if ($metadata)
{
$output->writeln(sprintf('Converting Doctrine 1 schema "<info>%s</info>"', $input->getArgument('d1-schema')));
foreach ($metadata as $class)
{
$className = $class->name;
$class->name = $namespace.'\\'.$bundleClass.'\\Entities\\'.$className;
if ($type === 'annotation')
{
$path = $destPath.'/'.$className.'.php';
}
else
{
$path = $destPath.'/'.str_replace('\\', '.', $class->name).'.dcm.xml';
}
$output->writeln(sprintf(' > writing <comment>%s</comment>', $path));
$code = $exporter->exportClassMetadata($class);
file_put_contents($path, $code);
}
} else {
$output->writeln('Database does not have any mapping information.'.PHP_EOL, 'ERROR');
}
}
}

View File

@ -29,19 +29,20 @@ use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand;
*/
class ConvertMappingDoctrineCommand extends ConvertMappingCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:convert-mapping');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to convert the mapping information from.');
$this
->setName('doctrine:mapping:convert')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to convert the mapping information from.')
->setHelp(<<<EOT
The <info>doctrine:mapping:convert</info> command converts mapping information between supported formats:
<info>./symfony doctrine:mapping:convert xml /path/to/output</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -29,39 +29,28 @@ use Doctrine\DBAL\Connection;
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class DatabaseToolDoctrineCommand extends DoctrineCommand
class CreateDatabaseDoctrineCommand extends DoctrineCommand
{
/**
* @see Command
*/
protected function configure()
{
$this
->setName('doctrine:database-tool')
->setDescription('Create and drop the configured databases.')
->addOption('re-create', null, null, 'Drop and re-create your databases.')
->addOption('drop', null, null, 'Drop your databases.')
->addOption('create', null, null, 'Create your databases.')
->addOption('connection', null, null, 'The connection name to work on.')
;
->setName('doctrine:database:create')
->setDescription('Create the configured databases.')
->addOption('connection', null, null, 'The connection name to create the database for.')
->setHelp(<<<EOT
The <info>doctrine:database:create</info> command creates the default connections database:
<info>./symfony doctrine:database:create</info>
You can also optionally specify the name of a connection to create the database for:
<info>./symfony doctrine:database:create --connection=default</info>
EOT
);
}
/**
* @see Command
*
* @throws \InvalidArgumentException When neither of --drop or --create is specified
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('re-create'))
{
$input->setOption('drop', true);
$input->setOption('create', true);
}
if (!$input->getOption('drop') && !$input->getOption('create'))
{
throw new \InvalidArgumentException('You must specify one of the --drop and --create options or both.');
}
$found = false;
$connections = $this->getDoctrineConnections();
foreach ($connections as $name => $connection)
@ -70,14 +59,7 @@ class DatabaseToolDoctrineCommand extends DoctrineCommand
{
continue;
}
if ($input->getOption('drop'))
{
$this->dropDatabaseForConnection($connection, $output);
}
if ($input->getOption('create'))
{
$this->createDatabaseForConnection($connection, $output);
}
$this->createDatabaseForConnection($connection, $output);
$found = true;
}
if ($found === false)
@ -93,20 +75,6 @@ class DatabaseToolDoctrineCommand extends DoctrineCommand
}
}
protected function dropDatabaseForConnection(Connection $connection, OutputInterface $output)
{
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path']:$params['dbname'];
try {
$connection->getSchemaManager()->dropDatabase($name);
$output->writeln(sprintf('<info>Dropped database for connection named <comment>%s</comment></info>', $name));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Could not drop database for connection named <comment>%s</comment></error>', $name));
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
}
}
protected function createDatabaseForConnection(Connection $connection, OutputInterface $output)
{
$params = $connection->getParams();

View File

@ -28,19 +28,25 @@ use Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand;
*/
class CreateSchemaDoctrineCommand extends CreateCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:create-schema');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to create the schema for.');
$this
->setName('doctrine:schema:create')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to create the schema for.')
->setHelp(<<<EOT
The <info>doctrine:schema:create</info> command creates the default entity managers schema:
<info>./symfony doctrine:schema:create</info>
You can also optionally specify the name of a entity manager to create the schema for:
<info>./symfony doctrine:schema:create --em=default</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -16,6 +16,7 @@ use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Tools\EntityGenerator;
/*
* This file is part of the Symfony framework.
@ -66,6 +67,18 @@ abstract class DoctrineCommand extends Command
$helperSet->set(new ConnectionHelper($connection), 'db');
}
protected function getEntityGenerator()
{
$entityGenerator = new EntityGenerator();
$entityGenerator->setGenerateAnnotations(false);
$entityGenerator->setGenerateStubMethods(true);
$entityGenerator->setRegenerateEntityIfExists(false);
$entityGenerator->setUpdateEntityIfExists(true);
$entityGenerator->setNumSpaces(2);
return $entityGenerator;
}
protected function getEntityManager($name = null)
{
$name = $name ? $name : 'default';

View File

@ -0,0 +1,91 @@
<?php
namespace Symfony\Framework\DoctrineBundle\Command;
use Symfony\Components\Console\Input\InputArgument;
use Symfony\Components\Console\Input\InputOption;
use Symfony\Components\Console\Input\InputInterface;
use Symfony\Components\Console\Output\OutputInterface;
use Symfony\Components\Console\Output\Output;
use Symfony\Framework\WebBundle\Util\Filesystem;
use Doctrine\Common\Cli\Configuration;
use Doctrine\Common\Cli\CliController as DoctrineCliController;
use Doctrine\DBAL\Connection;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* Database tool allows you to easily drop and create your configured databases.
*
* @package Symfony
* @subpackage Framework_DoctrineBundle
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class DropDatabaseDoctrineCommand extends DoctrineCommand
{
protected function configure()
{
$this
->setName('doctrine:database:drop')
->setDescription('Drop the configured databases.')
->addOption('connection', null, null, 'The connection name to create the database for.')
->setHelp(<<<EOT
The <info>doctrine:database:drop</info> command drops the default connections database:
<info>./symfony doctrine:database:drop</info>
You can also optionally specify the name of a connection to drop the database for:
<info>./symfony doctrine:database:drop --connection=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$found = false;
$connections = $this->getDoctrineConnections();
foreach ($connections as $name => $connection)
{
if ($input->getOption('connection') && $name != $input->getOption('connection'))
{
continue;
}
$this->dropDatabaseForConnection($connection, $output);
$found = true;
}
if ($found === false)
{
if ($input->getOption('connection'))
{
throw new \InvalidArgumentException(sprintf('<error>Could not find a connection named <comment>%s</comment></error>', $input->getOption('connection')));
}
else
{
throw new \InvalidArgumentException(sprintf('<error>Could not find any configured connections</error>', $input->getOption('connection')));
}
}
}
protected function dropDatabaseForConnection(Connection $connection, OutputInterface $output)
{
$params = $connection->getParams();
$name = isset($params['path']) ? $params['path']:$params['dbname'];
try {
$connection->getSchemaManager()->dropDatabase($name);
$output->writeln(sprintf('<info>Dropped database for connection named <comment>%s</comment></info>', $name));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Could not drop database for connection named <comment>%s</comment></error>', $name));
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
}
}
}

View File

@ -28,19 +28,25 @@ use Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand;
*/
class DropSchemaDoctrineCommand extends DropCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:drop-schema');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to drop the schema for.');
$this
->setName('doctrine:schema:drop')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to drop the schema for.')
->setHelp(<<<EOT
The <info>doctrine:schema:drop</info> command drops the default entity managers schema:
<info>./symfony doctrine:schema:drop</info>
You can also optionally specify the name of a entity manager to drop the schema for:
<info>./symfony doctrine:schema:drop --em=default</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -28,19 +28,25 @@ use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand;
*/
class EnsureProductionSettingsDoctrineCommand extends EnsureProductionSettingsCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:ensure-production-settings');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to ensure production settings for.');
$this
->setName('doctrine:ensure-production-settings')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to ensure production settings for.')
->setHelp(<<<EOT
The <info>doctrine:cache:clear-metadata</info> command clears all metadata cache for the default entity manager:
<info>./symfony doctrine:cache:clear-metadata</info>
You can also optionally specify the <comment>--em</comment> option to specify which entity manager to clear the cache for:
<info>./symfony doctrine:cache:clear-metadata --em=default</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -31,25 +31,20 @@ class GenerateEntitiesDoctrineCommand extends DoctrineCommand
{
protected function configure()
{
$this
->setName('doctrine:generate-entities')
$this
->setName('doctrine:generate:entities')
->setDescription('Generate entity classes and method stubs from your mapping information.')
->setHelp(<<<EOT
Generate entity classes and method stubs from your mapping information.
The <info>doctrine:generate:entities</info> command generates entity classes and method stubs from your mapping information:
<info>./symfony doctrine:generate:entities</info>
EOT
);
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$entityGenerator = new EntityGenerator();
$entityGenerator->setGenerateAnnotations(false);
$entityGenerator->setGenerateStubMethods(true);
$entityGenerator->setRegenerateEntityIfExists(false);
$entityGenerator->setUpdateEntityIfExists(true);
$entityGenerator->setNumSpaces(2);
$entityGenerator = $this->getEntityGenerator();
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
foreach ($this->container->getKernelService()->getBundles() as $bundle)
{

View File

@ -30,35 +30,30 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo;
*/
class GenerateEntityDoctrineCommand extends DoctrineCommand
{
/**
* @see Command
*/
protected function configure()
{
$this
->setName('doctrine:generate-entity')
->setName('doctrine:generate:entity')
->setDescription('Generate a new Doctrine entity inside a bundle.')
->addArgument('bundle', null, InputArgument::REQUIRED, 'The bundle to initialize the entity in.')
->addArgument('entity', null, InputArgument::REQUIRED, 'The entity class to initialize.')
->addOption('mapping-type', null, InputOption::PARAMETER_OPTIONAL, 'The mapping type to to use for the entity.')
->addOption('fields', null, InputOption::PARAMETER_OPTIONAL, 'The fields to create with the new entity.')
->setHelp('
The <info>doctrine:generate-entity</info> task initializes a new Doctrine entity inside a bundle:
->setHelp(<<<EOT
The <info>doctrine:generate:entity</info> task initializes a new Doctrine entity inside a bundle:
<comment>php console doctrine:generate-entity "Bundle\MyCustomBundle" "User\Group"</comment>
<comment>./symfony doctrine:generate:entity "Bundle\MyCustomBundle" "User\Group"</comment>
The above would initialize a new entity in the following entity namespace <info>Bundle\MyCustomBundle\Entities\User\Group</info>.
You can also optionally specify the fields you want to generate in the new entity:
<comment>php console doctrine:generate-entity "Bundle\MyCustomBundle" "User\Group" --fields="name:string(255) description:text"</comment>
')
;
<comment>./symfony doctrine:generate:entity "Bundle\MyCustomBundle" "User\Group" --fields="name:string(255) description:text"</comment>
EOT
);
}
/**
* @see Command
*
* @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle\MySampleBundle")
*/
protected function execute(InputInterface $input, OutputInterface $output)
@ -118,14 +113,7 @@ You can also optionally specify the fields you want to generate in the new entit
{
$path = $dirs[$namespace].'/'.$bundle.'/Entities/'.str_replace($entityNamespace.'\\', null, $fullEntityClassName).'.php';
$entityGenerator = new EntityGenerator();
$entityGenerator->setGenerateAnnotations(false);
$entityGenerator->setGenerateStubMethods(true);
$entityGenerator->setRegenerateEntityIfExists(false);
$entityGenerator->setUpdateEntityIfExists(false);
$entityGenerator->setNumSpaces(2);
$exporter->setEntityGenerator($entityGenerator);
$exporter->setEntityGenerator($this->getEntityGenerator());
} else {
$path = $dirs[$namespace].'/'.$bundle.'/Resources/config/doctrine/metadata/'.str_replace('\\', '.', $fullEntityClassName).'.dcm.xml';
}

View File

@ -28,19 +28,21 @@ use Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand;
*/
class GenerateProxiesDoctrineCommand extends GenerateProxiesCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:generate-proxies');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to generate proxies for.');
$this
->setName('doctrine:generate:proxies')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to generate proxies for.')
->setHelp(<<<EOT
The <info>doctrine:generate:proxies</info> command generates proxy classes for your entities:
<info>./symfony doctrine:generate:proxies</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -28,7 +28,15 @@ class GenerateRepositoriesDoctrineCommand extends DoctrineCommand
{
protected function configure()
{
$this->setName('doctrine:generate-repositories');
$this
->setName('doctrine:generate:repositories')
->setDescription('Generate repository classes from your mapping information.')
->setHelp(<<<EOT
The <info>doctrine:generate:repositories</info> command generates the configured entity repository classes from your mapping information:
<info>./symfony doctrine:generate:repositories</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)

View File

@ -0,0 +1,127 @@
<?php
namespace Symfony\Framework\DoctrineBundle\Command;
use Symfony\Components\Console\Input\InputArgument;
use Symfony\Components\Console\Input\InputOption;
use Symfony\Components\Console\Input\InputInterface;
use Symfony\Components\Console\Output\OutputInterface;
use Symfony\Components\Console\Output\Output;
use Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Doctrine\ORM\Mapping\Driver\DatabaseDriver;
use Doctrine\ORM\Tools\DisconnectedClassMetadataFactory;
use Doctrine\ORM\Tools\Export\ClassMetadataExporter;
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* Import Doctrine ORM metadata mapping information from an existing database.
*
* @package Symfony
* @subpackage Framework_DoctrineBundle
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class ImportMappingDoctrineCommand extends DoctrineCommand
{
protected function configure()
{
$this
->setName('doctrine:mapping:import')
->addArgument('bundle', InputArgument::REQUIRED, 'The bundle to import the mapping information to.')
->addArgument('mapping-type', InputArgument::OPTIONAL, 'The mapping type to export the imported mapping information to.')
->addArgument('em', InputArgument::OPTIONAL, 'The entity manager to import the mapping information from.')
->setDescription('Import mapping information from an existing database.')
->setHelp(<<<EOT
The <info>doctrine:mapping:import</info> command imports mapping information from an existing database:
<info>./symfony doctrine:mapping:import "Bundle\MyCustomBundle" xml</info>
You can also optionally specify which entity manager to import from with the <info>--em</info> option:
<info>./symfony doctrine:mapping:import "Bundle\MyCustomBundle" xml --em=default</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$bundleClass = null;
$bundleDirs = $this->container->getKernelService()->getBundleDirs();
foreach ($this->container->getKernelService()->getBundles() as $bundle)
{
if (strpos(get_class($bundle), $input->getArgument('bundle')) !== false)
{
$tmp = dirname(str_replace('\\', '/', get_class($bundle)));
$namespace = str_replace('/', '\\', dirname($tmp));
$class = basename($tmp);
if (isset($bundleDirs[$namespace]))
{
$destPath = realpath($bundleDirs[$namespace]).'/'.$class;
$bundleClass = $class;
break;
}
}
}
$type = $input->getArgument('mapping-type') ? $input->getArgument('mapping-type') : 'xml';
if ($type === 'annotation')
{
$destPath .= '/Entities';
}
else
{
$destPath .= '/Resources/config/doctrine/metadata';
}
$cme = new ClassMetadataExporter();
$exporter = $cme->getExporter($type);
if ($type === 'annotation')
{
$entityGenerator = $this->getEntityGenerator();
$exporter->setEntityGenerator($entityGenerator);
}
$emName = $input->getArgument('em') ? $input->getArgument('em') : 'default';
$emServiceName = sprintf('doctrine.orm.%s_entity_manager', $emName);
$em = $this->container->getService($emServiceName);
$databaseDriver = new DatabaseDriver($em->getConnection()->getSchemaManager());
$em->getConfiguration()->setMetadataDriverImpl($databaseDriver);
$cmf = new DisconnectedClassMetadataFactory($em);
$metadata = $cmf->getAllMetadata();
if ($metadata)
{
$output->writeln(sprintf('Importing mapping information from "<info>%s</info>" entity manager', $emName));
foreach ($metadata as $class)
{
$className = $class->name;
$class->name = $namespace.'\\'.$bundleClass.'\\Entities\\'.$className;
if ($type === 'annotation')
{
$path = $destPath.'/'.$className.'.php';
}
else
{
$path = $destPath.'/'.str_replace('\\', '.', $class->name).'.dcm.xml';
}
$output->writeln(sprintf(' > writing <comment>%s</comment>', $path));
$code = $exporter->exportClassMetadata($class);
file_put_contents($path, $code);
}
} else {
$output->writeln('Database does not have any mapping information.'.PHP_EOL, 'ERROR');
}
}
}

View File

@ -33,26 +33,33 @@ use Doctrine\ORM\Internal\CommitOrderCalculator;
*/
class LoadDataFixturesDoctrineCommand extends DoctrineCommand
{
/**
* @see Command
*/
protected function configure()
{
$this
->setName('doctrine:load-data-fixtures')
->setName('doctrine:data:load')
->setDescription('Load data fixtures to your database.')
->addOption('dir-or-file', null, InputOption::PARAMETER_OPTIONAL | InputOption::PARAMETER_IS_ARRAY, 'The directory or file to load data fixtures from.')
->addOption('fixtures', null, InputOption::PARAMETER_OPTIONAL | InputOption::PARAMETER_IS_ARRAY, 'The directory or file to load data fixtures from.')
->addOption('append', null, InputOption::PARAMETER_OPTIONAL, 'Whether or not to append the data fixtures.', false)
;
->setHelp(<<<EOT
The <info>doctrine:data:load</info> command loads data fixtures from your bundles:
<info>./symfony doctrine:data:load</info>
You can also optionally specify the path to fixtures with the <info>--fixtures</info> option:
<info>./symfony doctrine:data:load --fixtures=/path/to/fixtures1 --fixtures=/path/to/fixtures2</info>
If you want to append the fixtures instead of flushing the database first you can use the <info>--append</info> option:
<info>./symfony doctrine:data:load --append</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$defaultEm = $this->container->getDoctrine_ORM_EntityManagerService();
$dirOrFile = $input->getOption('dir-or-file');
$dirOrFile = $input->getOption('fixtures');
if ($dirOrFile)
{
$paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile);

View File

@ -28,19 +28,29 @@ use Doctrine\ORM\Tools\Console\Command\RunDqlCommand;
*/
class RunDqlDoctrineCommand extends RunDqlCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:run-dql');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to execute the DQL query on.');
$this
->setName('doctrine:query:dql')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to execute the DQL query on.')
->setHelp(<<<EOT
The <info>doctrine:query:dql</info> command executes the given DQL query and outputs the results:
<info>./symfony doctrine:query:dql "SELECT u FROM UserBundle:User u"</info>
You can also optional specify some additional options like what type of hydration to use when executing the query:
<info>./symfony doctrine:query:dql "SELECT u FROM UserBundle:User u" --hydrate=array</info>
Additionaly you can specify the first result and maximum amount of results to show:
<info>./symfony doctrine:query:dql "SELECT u FROM UserBundle:User u" --first-result=0 --max-result=30</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -28,19 +28,21 @@ use Doctrine\DBAL\Tools\Console\Command\RunSqlCommand;
*/
class RunSqlDoctrineCommand extends RunSqlCommand
{
/**
* @see RunSqlCommand
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:run-sql');
$this->addOption('connection', null, null, 'The connection to execute the SQL query on.');
$this
->setName('doctrine:query:sql')
->addOption('connection', null, null, 'The connection to execute the SQL query on.')
->setHelp(<<<EOT
The <info>doctrine:query:sql</info> command executes the given DQL query and outputs the results:
<info>./symfony doctrine:query:sql "SELECT * from user"</info>
EOT
);
}
/**
* @see RunSqlCommand
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationConnection($this->application, $input->getOption('connection'));

View File

@ -28,19 +28,25 @@ use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand;
*/
class UpdateSchemaDoctrineCommand extends UpdateCommand
{
/**
* @see Command
*/
protected function configure()
{
parent::configure();
$this->setName('doctrine:update-schema');
$this->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to update the schema for.');
$this
->setName('doctrine:schema:update')
->addOption('em', null, InputOption::PARAMETER_OPTIONAL, 'The entity manager to update the schema for.')
->setHelp(<<<EOT
The <info>doctrine:schema:update</info> command updates the default entity managers schema:
<info>./symfony doctrine:schema:update</info>
You can also optionally specify the name of a entity manager to update the schema for:
<info>./symfony doctrine:schema:update --em=default</info>
EOT
);
}
/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
DoctrineCommand::setApplicationEntityManager($this->application, $input->getOption('em'));

View File

@ -114,12 +114,12 @@ which contains the following XML:
</doctrine-mapping>
## Building Entities
## Generating Entities
Doctrine can help you a little bit by generating the entity classes for your
mapping information with the command:
$ php console doctrine:build-entities
$ php console doctrine:generate:entities
Now if you have a look in the bundles **Entities** directory you will see a new
file named **Entry.php** with some code like the following:
@ -135,15 +135,15 @@ file named **Entry.php** with some code like the following:
*/
class Entry
{
/**
* @Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* @Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* @Column(name="name", type="string", length=255)
*/
private $name;
/**
* @Column(name="name", type="string", length=255)
*/
private $name;
// ...
@ -161,20 +161,25 @@ commands we need to make working with Doctrine 2 just as easy and fast as before
$ php console list doctrine
Available commands for the "doctrine" namespace:
:build Build task for easily re-building your Doctrine development environment.
:build-entities Build all Bundle entity classes from mapping information.
:clear-cache Clear cache from configured query, result and metadata drivers. (doctrine:cc)
:convert-mapping Convert mapping information between supported formats.
:database-tool Create and drop the configured databases.
:cache:clear-metadata Clear all metadata cache for a entity manager.
:cache:clear-query Clear all query cache for a entity manager.
:cache:clear-result Clear result cache for a entity manager.
:data:load Load data fixtures to your database.
:database:create Create the configured databases.
:database:drop Drop the configured databases.
:ensure-production-settings Verify that Doctrine is properly configured for a production environment.
:generate-proxies Generates proxy classes for entity classes.
:import-mapping Import the initial mapping information for entities from an existing database.
:init-entity Initialize a new Doctrine entity inside a bundle.
:load-data-fixtures Load data fixtures to your database.
:run-dql Executes arbitrary DQL directly from the command line.
:run-sql Executes arbitrary SQL from a file or directly from the command line.
:schema-tool Processes the schema and either apply it directly on EntityManager or generate the SQL output.
:version Displays the current installed Doctrine version.
:generate:entities Generate entity classes and method stubs from your mapping information.
:generate:entity Generate a new Doctrine entity inside a bundle.
:generate:proxies Generates proxy classes for entity classes.
:generate:repositories Generate repository classes from your mapping information.
:mapping:convert Convert mapping information between supported formats.
:mapping:convert-d1-schema Convert a Doctrine 1 schema to Doctrine 2 mapping files.
:mapping:import Import mapping information from an existing database.
:query:dql Executes arbitrary DQL directly from the command line.
:query:sql Executes arbitrary SQL directly from the command line.
:schema:create Processes the schema and either create it directly on EntityManager Storage Connection or generate the SQL output.
:schema:drop Processes the schema and either drop the database schema of EntityManager Storage Connection or generate the SQL output.
:schema:update Processes the schema and either update the database schema of EntityManager Storage Connection or generate the SQL output.
### Schema Tool
@ -183,68 +188,30 @@ database schemas for your mapping information.
You can easily create your initial schema from mapping information:
php console doctrine:schema-tool --create
php console doctrine:schema:create
Or if you want to then drop your schema you can do:
php console doctrine:schema-tool --drop
If you want to re-create it (drop and create) you can use:
php console doctrine:schema-tool --re-create
php console doctrine:schema:drop
Now the scenario arrises where you want to change your mapping information and
update your database without blowing away everything and losing your existing data.
You can do the following for that:
php console doctrine:schema-tool --update
php console doctrine:schema:update
> **TIP**
> The above will not drop anything from your database schema. To drop the remaining
> things from your schema you need to use the **--complete-update** option.
> things from your schema you need to use the **--complete** option.
>
> php console doctrine:schema-tool --complete-update
> php console doctrine:schema:update --complete
### Doctrine Build Command
### Doctrine Generate Entity Command
The development workflow is very similar to how it is in Symfony 1.4. You can modify
your mapping information and use **doctrine:build --all** to re-build your
environment:
You can easily generate a new Doctrine entity for a bundle by using the
**doctrine:generate-entity** command:
php console doctrine:build --all
The recommend way to work is to re-build your entities and update your database
schema:
php console doctrine:build --entities --and-update-schema
Now any changes you made in your mapping information will be reflected in the
according databases! Here are all the available options for the **build** task:
> **NOTE**
> Not the key difference here is that you can modify your schema during development
> and just update your database schema without having to blow everything away and
> re-build it all.
$ php console help doctrine:build
Usage:
Symfony doctrine:build [--all] [--all-classes] [--entities] [--db] [--and-load[="..."]] [--and-append[="..."]] [--and-update-schema] [--dump-sql] [--connection]
Options:
--all Build everything and reset the database
--entities Build model classes
--db Drop database, create database and create schema.
--and-load Load data fixtures (multiple values allowed)
--and-append Load data fixtures and append to existing data (multiple values allowed)
--and-update-schema Update schema after rebuilding all classes
--connection The connection to use.
### Doctrine Init Entity Command
You can easily initialize a new Doctrine entity for a bundle by using the
**doctrine:init-bundle** command:
$ php console doctrine:init-entity --bundle="Bundle\MySampleBundle" --entity="User\Group"
$ php console doctrine:generate:entity "Bundle\MySampleBundle" "User\Group" --fields="name:string(255) description:text"
Now if you have a look inside the bundle you will see that you have a **Group** class
located here **Bundle/MySampleBundle/Entities/User/Group.php**.
@ -253,4 +220,4 @@ Now you can customize the mapping information for the entity by editing the meta
information inside **Bundle/MySampleBundle/Resources/config/doctrine/metadata** and
just update your database schema:
$ php console doctrine:schema-tool --update
$ php console doctrine:schema:update