Symfony 3 - 自动生成BOOLEAN getter和setter - isActive vs getActive

Dev*_*123 10 doctrine getter-setter symfony phpstorm

自动生成BOOLEAN getter和setter - 不同的输出

Symfony3.2.0:php bin/console vs PhpStorm 2016.3

如果我使用命令行或在Entity类中的BOOLEAN值上使用PhpStorm函数,则生成的代码似乎有所不同.doctrine:generate:entitiesGenerate - Getters and Setters

示例:我已经设置了这个私有变量,下面是3个生成Getters/Setter的示例,它们都给出了略有不同的输出.

/**
 * @var boolean
 * @ORM\Column(name="active", type="boolean")
 */
private $active;

# Generated 'getter' from command line = getActive()
# Generated 'getter' from PhpStorm = isActive()
Run Code Online (Sandbox Code Playgroud)

控制台命令:( php bin/console doctrine:generate:entities MyBundle:MyEntity 注意:getActive,返回布尔值)

/**
 * Set active
 *
 * @param boolean $active
 *
 * @return MyEntity
 */
public function setActive($active)
{
    $this->active = $active;

    return $this;
}

/**
 * Get active
 *
 * @return boolean
 */
public function getActive()
{
    return $this->active;
}
Run Code Online (Sandbox Code Playgroud)

PhpStorm中 - 代码>生成(Alt + Insert)> Getters和Setter(启用复选框'Fluent setters' )(注意:isActive,返回bool)

/**
 * @return bool
 */
public function isActive()
{
    return $this->active;
}

/**
 * @param bool $active
 * @return MyEntity
 */
public function setActive($active)
{
    $this->active = $active;
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

另一个: PhpStorm - 代码>生成(Alt +插入)> Getters和Setter(复选框'Fluent setters' 禁用)(注意:isActive,返回bool和setActive不返回$ this)

/**
 * @return bool
 */
public function isActive()
{
    return $this->active;
}

/**
 * @param bool $active
 */
public function setActive($active)
{
    $this->active = $active;
}
Run Code Online (Sandbox Code Playgroud)

我的问题:

  1. 可以在命令行工具doctrine:generate:entities以某种方式配置以产生用于布尔值干将自动is...以"让......"代替?(这样它总是产生布尔getter方法为:isActive(),isEnabled(),等等)

  2. 我看到了一些示例/教程,其中方法setActive() 没有返回$this,因此不能使用链接.返回是最佳做法$this吗?什么是首选方式?(当你返回时有不利之处$this,表现可能吗?)

  3. 注释部分中返回类型的微小差异是否对应用程序有任何影响(使用命令行进行数据库迁移)?或者Symfony 中的各种类型boolboolean处理方式相同?

(3.例子)

@return bool (Generated by command line)
vs
@return boolean (Generated by PhpStorm)
Run Code Online (Sandbox Code Playgroud)

Ste*_*hka 1

我已经使用了一些代码,不幸的是没有办法用现有的设置来生成它。所有类都是硬编码的,无法使用命令或 Symfony 设置来覆盖它。

因此,我对生成器类进行了一些扩展,并创建了接受生成器作为参数的扩展命令。我还创建了示例生成器,它创建了用于设置布尔值的“is...”方法。

不幸的是,存在一些来自现有类的复制粘贴,因为无法扩展它。

回答第二个问题我认为使用流畅的界面更符合个人喜好。我是老派开发人员,不习惯 PHP 中流畅的界面。我没有看到它对性能有任何重大影响。

对于第三个问题。bool和之间的区别boolean在于bool标量类型声明,而boolean是变量类型。请参阅文档中的“警告”。它解释了很多。

<?php
// src/AppBundle/Command/GenerateDoctrineEntityExtendedCommand.php
namespace AppBundle\Command;

use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineEntityCommand;
use Sensio\Bundle\GeneratorBundle\Generator\Generator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateDoctrineEntityExtendedCommand extends GenerateDoctrineEntityCommand
{
    /** @var Generator */
    private $generator;

    protected function configure()
    {
        parent::configure();
        $this->setName('doctrine:generate:entity:extended');
        $this->setDescription($this->getDescription() . " Allows specifying generator class.");
        $this->addOption('generator', null, InputOption::VALUE_REQUIRED, "The generator class to create entity.", 'Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator');
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        parent::initialize($input, $output);
        if ($class = $input->getOption('generator')) {
            if (!class_exists($class)) {
                throw new \Exception('Class ' . $class . 'does not exist.');
            }
            $this->generator = new $class($this->getContainer()->get('filesystem'), $this->getContainer()->get('doctrine'));
        }
    }

    protected function createGenerator()
    {
        return $this->generator;
    }
}
Run Code Online (Sandbox Code Playgroud)

DoctrineEntityGenerator 替换:

<?php
// src/AppBundle/Generator/IsDoctrineEntityGenerator.php
namespace AppBundle\Generator;

use Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator;

class IsDoctrineEntityGenerator extends DoctrineEntityGenerator
{
    protected function getEntityGenerator()
    {
        // This is the place where customized entity generator is instantiated instead of default
        $entityGenerator = new IsEntityGenerator();
        $entityGenerator->setGenerateAnnotations(false);
        $entityGenerator->setGenerateStubMethods(true);
        $entityGenerator->setRegenerateEntityIfExists(false);
        $entityGenerator->setUpdateEntityIfExists(true);
        $entityGenerator->setNumSpaces(4);
        $entityGenerator->setAnnotationPrefix('ORM\\');

        return $entityGenerator;
    }
}
Run Code Online (Sandbox Code Playgroud)

实体生成器替换:

<?php
// src/AppBundle/Generator/IsEntityGenerator.php
namespace AppBundle\Generator;

use Doctrine\Common\Inflector\Inflector;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Tools\EntityGenerator;
use Doctrine\DBAL\Types\Type;

class IsEntityGenerator extends EntityGenerator
{
    protected function generateEntityStubMethod(ClassMetadataInfo $metadata, $type, $fieldName, $typeHint = null, $defaultValue = null)
    {
        //
        // This is the only line I've added compared to the original method
        //
        $methodPrefix = ($type == 'get' && $typeHint == 'boolean') ? 'is' : $type;
        $methodName = $methodPrefix . Inflector::classify($fieldName);

        $variableName = Inflector::camelize($fieldName);
        if (in_array($type, array("add", "remove"))) {
            $methodName = Inflector::singularize($methodName);
            $variableName = Inflector::singularize($variableName);
        }

        if ($this->hasMethod($methodName, $metadata)) {
            return '';
        }
        $this->staticReflection[$metadata->name]['methods'][] = strtolower($methodName);

        $var = sprintf('%sMethodTemplate', $type);
        $template = static::$$var;

        $methodTypeHint = null;
        $types = Type::getTypesMap();
        $variableType = $typeHint ? $this->getType($typeHint) : null;

        if ($typeHint && !isset($types[$typeHint])) {
            $variableType = '\\' . ltrim($variableType, '\\');
            $methodTypeHint = '\\' . $typeHint . ' ';
        }

        $replacements = array(
            '<description>' => ucfirst($type) . ' ' . $variableName,
            '<methodTypeHint>' => $methodTypeHint,
            '<variableType>' => $variableType,
            '<variableName>' => $variableName,
            '<methodName>' => $methodName,
            '<fieldName>' => $fieldName,
            '<variableDefault>' => ($defaultValue !== null) ? (' = ' . $defaultValue) : '',
            '<entity>' => $this->getClassName($metadata)
        );

        $method = str_replace(
            array_keys($replacements),
            array_values($replacements),
            $template
        );

        return $this->prefixCodeWithSpaces($method);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以恐怕这是迄今为止您想要的唯一选择。