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

时间:2016-12-08 16:38:09

标签: doctrine phpstorm symfony getter-setter

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

Symfony3.2.0:php bin / console vs PhpStorm 2016.3

如果我使用命令行doctrine:generate:entities或在Entity类中的BOOLEAN值上使用PhpStorm函数Generate - Getters and Setters,则生成的代码中似乎存在差异。 / p>

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

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

# Generated 'getter' from command line = getActive()
# Generated 'getter' from PhpStorm = isActive()

控制台命令: 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;
}

PhpStorm - 代码>生成(Alt + Insert)> Getters and Setters(带有复选框'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;
}

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

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

/**
 * @param bool $active
 */
public function setActive($active)
{
    $this->active = $active;
}

我的问题:

  1. 命令行工具doctrine:generate:entities是否可以某种方式配置以生成布尔值自动的getter,而不是'{1}}而不是'get ...'? (以便始终生成布尔getter方法: is...isActive() 等)

  2. 我看到一些示例/教程,方法isEnabled() 没有返回setActive() ,因此不能使用链接。返回$this是最佳做法吗?什么是首选方式? (当你返回$this时,性能可能会有缺点吗?)

  3. 评论部分中返回类型的细微差别是否会对应用程序产生影响(使用命令行进行数据库迁移)?或者类型$thisbool在Symfony中的处理方式是否相同?

  4. (3.示例)

    boolean

2 个答案:

答案 0 :(得分:1)

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

所以我稍微扩展了生成器类并创建了接受生成器作为参数的扩展命令。我还创建了样本生成器,创建了'是...'设置布尔值的方法。

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

回答第二个问题我认为使用流畅的界面更加个人偏好。我是一名老派开发人员,而且我不习惯在PHP中使用流畅的界面。我认为没有任何重大的性能影响。

对于第3个问题。 boolboolean之间的区别在于boolscalar type declarationboolean是变量类型。请参阅'警告'在文档中。它解释了很多。

<?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;
    }
}

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;
    }
}

EntityGenerator替换:

<?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);
    }
}

所以,我害怕到目前为止你想要的唯一选择。

答案 1 :(得分:0)

Stepashka正确回答。

但我认为有一种更好,更简洁,更传统的方式可以帮助您使用PhpStorm自动生成与Symfony的Getters和Setters方法。

您可以自定义PhpStorm Getters和Setters生成方法!

你只需要去: 偏好设置/编辑器/文件和代码模板/代码

然后对于Getter,要将isActive修改为getActive,您必须将“PHP Getter Method”更改为:

/*
 * @return ${TYPE_HINT}
 */
public ${STATIC} function get${NAME}()#if(${RETURN_TYPE}): ${RETURN_TYPE}#else#end
{
#if (${STATIC} == "static")
    return self::$${FIELD_NAME};
#else
    return $this->${FIELD_NAME};
#end
}
对于Setter,要添加“return $ this”,你必须将“PHP Setter Method”更改为:

/*
 * @param ${TYPE_HINT} $${PARAM_NAME}
 * @return ${CLASS_NAME}
 */
public ${STATIC} function set${NAME}(#if (${SCALAR_TYPE_HINT})(${SCALAR_TYPE_HINT} #else#end$${PARAM_NAME})
{
#if (${STATIC} == "static")
    self::$${FIELD_NAME} = $${PARAM_NAME};
#else
    $this->${FIELD_NAME} = $${PARAM_NAME};
#end
    return $this;
}

最后,不要忘记应用更改。