我的问题围绕着魔法方法。
这是一个小小的例子:
$context = new Context('Entities.xml');
$user_array = $context->Users;
$user = $context->Users->find(array('name' => 'John Smith'));第二行返回包含所有用户对象的数组。第三行只返回名为John的用户对象。
我想知道这是否可能,棘手的部分是我不知道Context class的属性。它们是从用户在实例化时提供的xml文件中生成的,并且可以通过神奇的getter和setter访问。
Context示例(不完整,只是为了给出一个想法):
class Context {
private $path, $entities;
public function __construct($path) {
$this->path = $path;
}
public function __get($name) {
return $entities[$name];
}
public function __set($name, $arg) {
$entities[$name] = $arg;
}
}发布于 2014-03-13 07:38:33
因为我真的需要一个解决方案,所以我实现了以下解决方案。
Context类的getter返回一个处理结果的ResultLayer类。
示例:
class ResultLayer implements IteratorAggregate {
public $data = array();
private $entity, $context;
public function __construct($context, $entity) {
$this->context = $context;
$this->entity = $entity;
}
public function getIterator() {
return new ArrayIterator($this->data);
}
public function get($index) {
return $this->data[$index];
}
public function toArray() {
return $this->data;
}
public function find($properties) {
return $this->context->getEntity($this->entity, $properties);
}
}我已经实现了IteratorAggregate接口,以便您可以使用foreach循环,例如,遍历$Context->Users,这使代码更加可读性。
如果有人有更好的方法,我还是会接受的。任何帮助都是非常感谢的!
https://stackoverflow.com/questions/22324615
复制相似问题