如何将来自外部源的数据作为 DocumentSet 返回?
我设置了一个自定义数据源来与亚马逊的产品广告 API 交互。为此,我按照文档 ( http://li3.me/docs/manual/working-with-data/creating-data-sources.wiki )lithium\data\source\Http
中的描述对 read 方法进行了子类化和重新定义以满足我的需求。
但是,我的锂版本(0.11,最后一个版本)似乎没有像示例中那样的 cast 方法,如果我创建一个,它不会在我这样做时被调用return $this->item($model, $data, $options)
。
因此,我创建了一个自定义item
函数来创建文档,parent::item
就像文档示例对cast
. 然后,在递归调用之后,我得到了一个Document 对象数组,最后一次调用parent::item
then 给了我一个空的 DocumentSet 对象。我应该如何传递数据以创建正确的 DocumentSet?
这是我的代码的最小示例:
// Within class Amazon extends \lithium\data\source\Http
protected function _init() {
// Define entity classes.
$this->_classes += array(
'entity' => 'lithium\data\entity\Document',
'set' => 'lithium\data\collection\DocumentSet'
);
parent::_init();
}
public function read($query, array $options = array()) {
// Extract from query object.
$parameters = $query->export($this, array('keys' => array('conditions')));
$conditions = $parameters['conditions'];
// Code stripped to validate conditions and prepare Amazon request (that part works).
// results in a $queryString variable.
// Get response from Server.
$xml = simplexml_load_string($this->connection->get($this->_config['basePath'], $queryString));
// Stripped response validation and reformatting -> $items contains an array of SimpleXMLElement objects.
return $this->item($query->model(), $items, array('class' => 'set'));
}
public function item($model, array $data = array(), array $options = array()) {
// Recursively create Documents for arrays.
foreach($data as $key => $value) {
if(is_array($value)) {
$data[$key] = $this->item($model, $value, array('class' => 'entity'));
}
else if(is_object($value) && get_class($value) == "SimpleXMLElement") {
// Stripped code to extract data from XML object and put it in array $docData.
$data[$key] = $this->item($model, $docData, array('class' => 'entity'));
}
}
// Works perfectly for every (recursive) call with $options['class'] == 'entity' but fails for the final call with $options['class'] == 'set' (for this final call $data contains an array of Document objects).
return parent::item($model, $data, $options);
}