2010-09-10 113 views
11

可以说我有一个数组,我想要转换为一个值对象。PHP动态类加载

我的值对象类如下:

/* file UserVO.php*/ 
class UserVO 
{ 
    public $id; 
    public $email; 

    public function __construct($data) 
    { 
     $this->id = (int)$data['id']; 
     $this->email = $data['email']; 
    } 
} 

我创造我的值对象的数组如下:

/* file UserService.php*/ 
$array = array(
array(...), 
array(...)); 
$count = count($array); 
for ($i = 0; $i < $count; $i++) 
{ 
    $result[] = new UserVO($array[$i]); 
} 
return $result; 

好了,这一切工作正常。不过,我想特别指出要动态创建的VO,以便我可以有一个动态函数来创建我的VO。

喜欢的东西:

$ret = create_vo($array, 'UserVO'); 

function create_vo($data, $vo) 
{ 
    $count = count($data); 
    for ($i = 0; $i < $count; $i++) 
    { 
    $result[] = new $vo($data[$i]); //this obviously wont work...Class name must be a valid object or a string 
    } 
    return $result; 
} 

我意识到,我可以用一个switch语句做到这一点(通过遍历所有的VO的)......但毫无疑问更更好的解决方案。如果我可以根据需要延迟加载VO,也可以是supercool,而不是有多个“包含”。

任何帮助都很感激。

回答

13
$result[] = new $vo($data[$i]); //this obviously wont work...Class name must be a valid object or a string 

你试过了吗?它的工作方式与预期的一样(在PHP 5.1中,我不知道如何在PHP 4中使用OOP,但如果您使用构造函数__construct,这应该可以工作)。

为避免多次包括使用任何类

function __autoload($className) 
{ 
    require_once 'myclasses/'.$className.'.php'; 
} 

所以第一次调用new UserVo将触发此功能,包括文件myclasses/UserVo.php之前定义的神奇功能__autoload

0

首先,数据为UserVO数组对象的转换应该与ArrayObject的

所以

class UserVO extends ArrayObject 
{ 
} 

您正在尝试使用factory method pattern和你的代码似乎是正确的做,但你似乎忘记将$ result定义为一个数组($ result = array())。

您还可以使用ReflectionClass通过构造函数的参数以及这样:

$rc = new ReflectionClass($vo); 
$rc->newInstanceArgs($data[$i]); 

为“自动加载”你UserVO对象时,你应该使用spl_autoload_register功能与一个PHP包括路径。

0

这工作

<? 

class UserVO 
{ 
    public $id; 
    public $email; 

    public function loadData($data) 
    { 
     $this->id = (int)$data['id']; 
     $this->email = $data['email']; 
    } 
} 

function create_vo($data, $vo) 
{ 
    $count = count($data); 
    for ($i = 0; $i < $count; $i++) 
    { 
     $tmpObject = new $vo; 
     $tmpObject->loadData($data[$i]); 
     $result[] = $tmpObject; 
     unset($tmpObject); 
    } 
    return $result; 
} 


$data = array(); 
$data[] = array('id'=>1,'email'=>'[email protected]'); 
$data[] = array('id'=>2,'email'=>'[email protected]'); 
$data[] = array('id'=>3,'email'=>'[email protected]'); 
$data[] = array('id'=>4,'email'=>'[email protected]'); 
$data[] = array('id'=>5,'email'=>'[email protected]'); 
$data[] = array('id'=>6,'email'=>'[email protected]'); 

$result = create_vo($data,'UserVO'); 

var_dump($result); 

?> 
1

看来,include_once()'s and require_once()'s performance is pretty bad

我的建议:

杀死所有 “require_once” 和 “include_once”,并创建一个自动加载。注册此implementation

+0

您的自动加载程序仍然使用包含或要求它不会不断加载每一件事情只有当他们需要,所以你的论点是不是最有效的。因为使用自动装载机的负载更大。 – 2015-02-20 13:12:32