Doctrine orm 原则2定义属性类型而不创建列

Doctrine orm 原则2定义属性类型而不创建列,doctrine-orm,zend-framework2,zend-framework3,laminas,Doctrine Orm,Zend Framework2,Zend Framework3,Laminas,我有一个地址实体,它绑定到ZF/Lamas表单 定义了一些属性。例如街道、乡村 /** * @var string * * @ORM\Column(type="string", length=2) */ protected $country; /** * @var float * * @ORM\Column(type="float", nullable=true) */ protected $longitude; /** * @var float * * @ORM\Co

我有一个地址实体,它绑定到ZF/Lamas表单

定义了一些属性。例如街道、乡村

/**
 * @var string
 *
 * @ORM\Column(type="string", length=2)
 */
protected $country;

/**
 * @var float
 *
 * @ORM\Column(type="float", nullable=true)
 */
protected $longitude;

/**
 * @var float
 *
 * @ORM\Column(type="float", nullable=true)
 */
protected $latitude;
以及一个非存储属性,用于通过EventListener强制进行地理定位

/**
 * @var bool
 */
protected $geolocation = true;
使用访问者

/**
 * @param bool $geolocation
 *
 * @return self
 */
public function setGeolocation(bool $geolocation): self
{
    $this->geolocation = $geolocation;

    return $this;
}
问题是在水化过程中通过接入器。“geolocation”的值来自字符串类型“1”或“0”中的表单(复选框)

水合由DoctrineObject水合器进行,但属性不由ORM管理。因此,在启用严格类型模式的情况下,由于setGeolocation()参数类型,将引发异常

它应该与
@ORM\Column(type=“boolean”)
一起使用,但我不想存储此值


如何在不在db中创建列的情况下定义实体属性?

我认为您在原则或规范方面没有问题,您在类型转换方面有问题

当该值来自
lamas\Form\Form
对象时,应使用
InputFilter
将该值转换为带过滤器的bool。然后,中的
对象过滤器
应获取输入过滤器中的值

让我们看一看我的例子(为了简单起见,我这里不使用教义):


作为旁注:不要过度使用流畅的界面,它们会让人感觉到。
<?php

declare(strict_types=1);

class MyEntity
{

    private bool $mycheckbox = false;

    public function getMycheckbox(): bool
    {
        return $this->mycheckbox;
    }

    public function setMycheckbox(bool $mycheckbox): void
    {
        $this->mycheckbox = $mycheckbox;
    }

}

use Laminas\Form\Form;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Form\Element;
use Laminas\Filter;
use Laminas\Hydrator\ClassMethods as Hydrator;

class MyForm extends Form implements InputFilterProviderInterface
{

    public function init(): void
    {
        $this->add([
            'name'    => 'mycheckbox',
            'type'    => Element\Checkbox::class,
            'options' => [],
        ]);

        $this->setObject(new MyEntity());
        $this->setHydrator(new Hydrator());
    }

    public function getInputFilterSpecification(): array
    {
        return [
            'mycheckbox' => [
                'filters' => [
                    // this filter is the important part
                    [
                        'name'    => Filter\Boolean::class,
                        'options' => [],
                    ]
                ],
            ],
        ];
    }

}

$form = new MyForm();
$form->init();

$form->setData(['mycheckbox' => '1']);
var_dump($form->isValid());
var_dump($form->getInputFilter()->getValues());


var_dump($form->getObject());
bool(true)
array(1) {
   'mycheckbox' =>
   bool(true)
}

class MyEntity#9 (1) {
   private $mycheckbox =>
   bool(true)
}