Пользовательские сценарии генерации Symfony для сущностей

Мне просто интересно, есть ли способ изменить сценарии создания сущностей (вызывается с помощью generate: doctrine: entity).

Например, скрипт создает EntityRepository, как это

use Doctrine\ORM\EntityRepository;

/**
* FreeTokenRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class FreeTokenRepository extends EntityRepository
{
}

но я хотел бы, чтобы EntityRepository расширял мой собственный подкласс Repository (а также использовал различные соглашения для скобок), как это

use AppBundle\Model\Repository;

/**
* FreeTokenRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class FreeTokenRepository extends Repository {
}

Есть ли способ настроить сценарии создания сущностей symfony / doctrine? И все сценарии других поколений? Так что мне не нужно каждый раз менять свои автоматически созданные классы?

1

Решение

Мы создали нашу собственную команду для этого. Я поделюсь с вами здесь кодом, потому что он, кажется, идеально соответствует вашим требованиям.

Конечно, вам придется адаптировать некоторые папки и т. Д., Но в основном это делает именно то, что вы просите.
Просто настройте его на другие ваши потребности.

Просто вызовите app (Symfony 2) или bin (Symfony 3) / console company: createrepository MyEntity Extends, и он создаст ваш файл репозитория.

<?php

namespace Company\MyBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\HttpKernel\Kernel;

/**
* Creates a Repository File for a given Entity Class
*
* You will find a file called EntityRepository.php in Repositories folder
* Reformat the output code and enjoy
*
*
*/
class CreaterepositoryCommand extends ContainerAwareCommand
{
/**
*
*/
protected function configure()
{
$this
->setName('company:createrepository')
->setDescription('Create an Repository for entity class')
->addArgument('entity', InputArgument::REQUIRED, 'Enter an entity class name')
->addArgument(
'extends',
InputArgument::OPTIONAL,
'Enter which other Repository should be extended');
}

/**
* @param InputInterface  $input
* @param OutputInterface $output
*
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{

$manualEntity = $input->getArgument('entity');

if ($input->getArgument('extends')) {
$extends = $input->getArgument('extends') . "Repository";
$use = '';
} else {
$extends = "EntityRepository";
$use = '
use Doctrine\ORM\EntityRepository;
';
}

$fileContent = '
<?php

namespace Company\MyBundle\Entity\Repositories;
' . $use . '
class ' . $manualEntity . 'Repository extends ' . $extends . '
{

} ';

/** @var Kernel $kernel */
$kernel = $this->getContainer()->get('kernel');
$path = $kernel->locateResource('@CompanyMyBundle');
$path .= 'Entity/Repositories';
$fileName = $manualEntity . "Repository.php";
$fileNameInclPath = $path . "/" . $fileName;

if (file_exists($fileNameInclPath)) {
$helper = $this->getHelper('question');
$question = new ConfirmationQuestion(
'<fg=blue>File: </fg=blue>' . $fileName . '<fg=blue> already exists Overwrite?</fg=blue>',
false);

if (!$helper->ask($input, $output, $question)) {
$output->writeln('<fg=red>Aborted by user.</fg=red>');
} else {
$fp = fopen($fileNameInclPath, "wb");
fwrite($fp, $fileContent);
fclose($fp);
$output->writeln('<fg=green>File:</fg=green> ' . $fileName . '<fg=green> created</fg=green>');
}
} else {
$fp = fopen($fileNameInclPath, "wb");
fwrite($fp, $fileContent);
fclose($fp);
$output->writeln('<fg=green>File:</fg=green> ' . $fileName . '<fg=green> created</fg=green>');
}
}
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector