php - 教义 : Convert array to Doctrine entity

标签 php arrays doctrine-orm

我正在寻找一种将数组转换为学说实体的方法。我正在使用原则 2。

我有一个实体类,例如:

class User
{


    /**
     * @Id
     * @Column(type="integer", nullable=false)
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @Column(type="string", length=255, unique=true, nullable=false)
     */
    protected $email;

    /**
     * @Column(type="string", length=64, nullable=false)
     */
    protected $password;
    /**
     * @var DateTime
     * @Column(type="datetime", nullable=false)
     */
    protected $dob;

    //getter and setters
}

当我从 html 表单发布数据时,我想将 post 数组转换为 User 实体。所以我有一个像这样的数组

$userAsArray = array("email"=>"abc@xyz.com","password"=>"hello","dob"=>"10\20\1990");

$user = new User();

covert($userAsArray,$user) // I am looking for something like this

我正在寻找一种通用方法来完成此任务。我尝试过这样的事情:

 function fromArray(array $array,$class){
        $user = new $class();
        foreach($array as $key => $field){
            $keyUp = ucfirst($key);
            if(method_exists($user,'set'.$keyUp)){
                call_user_func(array($user,'set'.$keyUp),$field);
            }

        }
        return $user;
    }

但问题是它将所有内容设置为字符串。但对于日期,我想将其作为 DateTime 对象。有什么帮助吗?

最佳答案

如果数组元素之一是外键怎么办?在设置实体属性之前,您可能需要准备外键属性。这就是我完成类似任务的方法:

扩展存储库

<?php
namespace My\Doctrine;
use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository
{
    /**
     * Prepare attributes for entity 
     * replace foreign keys with entity instances
     * 
     * @param array $attributes entity attributes
     * @return array modified attributes values 
     */
    public function prepareAttributes(array $attributes)
    {
        foreach ($attributes as $fieldName => &$fieldValue) {
            if (!$this->getClassMetadata()->hasAssociation($fieldName)) {
                continue;
            }

            $association = $this->getClassMetadata()
                ->getAssociationMapping($fieldName);

            if (is_null($fieldValue)) {
                continue;
            }

            $fieldValue = $this->getEntityManager()
                ->getReference($association['targetEntity'], $fieldValue);

            unset($fieldValue);    
        }

        return $attributes;
    }
}

创建父Entity类:

namespace My\Doctrine;

class Entity
{
    /**
     * Assign entity properties using an array
     * 
     * @param array $attributes assoc array of values to assign
     * @return null 
     */
    public function fromArray(array $attributes)
    {
        foreach ($attributes as $name => $value) {
            if (property_exists($this, $name)) {
                $methodName = $this->_getSetterName($name);
                if ($methodName) {
                    $this->{$methodName}($value);
                } else {
                    $this->$name = $value;
                }
            }
        }
    }

    /**
     * Get property setter method name (if exists)
     * 
     * @param string $propertyName entity property name
     * @return false|string 
     */
    protected function _getSetterName($propertyName)
    {
        $prefixes = array('add', 'set');

        foreach ($prefixes as $prefix) {
            $methodName = sprintf('%s%s', $prefix, ucfirst(strtolower($propertyName)));

            if (method_exists($this, $methodName)) {
                return $methodName;
            }
        }
        return false;
    }
}

用法,您的存储库中的方法:

$entity = new User();
$attributes = array(
    "email"    =>"abc@xyz.com",
    "password" =>"hello",
    "dob"      =>"10\20\1990"));
$entity->fromArray($this->prepareAttributes($attributes));
$this->getEntityManager()->persist($entity);
$this->getEntityManager()->flush();    

关于php - 教义 : Convert array to Doctrine entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20254144/

相关文章:

php - PHP 中的数组是作为值复制还是作为对新变量的引用,以及何时传递给函数?

php - 使用 PHP 的 fputcsv 时如何写引号 ("")

javascript - PHP Ajax 返回 HTML 两次

arrays - Bash:awk 输出到数组

doctrine-orm - 在doctrine2实体中获取列名

javascript - 检查MySQL数据是否已存在,如果不存在则INSERT。 [PHP+jQuery Ajax]

ios - NSArray,试图将数组中对象的索引号传递给函数

c++ - 解析字节数组中的 Unicode

php - 原则 2 - 从实体外部禁用 PrePersist

sql - Doctrine - Symfony 3 querybuilder COUNT() 是错误的