【发布时间】:2013-11-27 22:18:16
【问题描述】:
我正在寻找一种将数组转换为学说实体的方法。我正在使用学说 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 表单发布数据时,我想将发布数组转换为用户实体。所以我有一个像
这样的数组$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 arrays doctrine-orm