Вопрос

Я реализую пользовательский источник данных в моем приложении CakePhP, я реализовал основные функции для данных DataSource (read(), listSources(), describe()). DataSource использует XML в качестве ввода, и мне очень хотелось бы использовать находку («соседей») на XML и было заданным вопросом, если торт «автоматически» реализует эту функцию (потому что read() Функция там), или если мне нужно как-то продлить источник данных. Я еще не нашел конкретный пример, поэтому я надеюсь, что поэтому сообщество сможет помочь.

Ниже приведена реализация текущей даты данных.

<?php
App::import('Core', 'Xml');

class AppdataSource extends DataSource {
  protected $_schema = array(
  'apps' => array(
   'id' => array(
    'type' => 'integer',
    'null' => true,
    'key' => 'primary',
    'length' => 11,
   ),
   'type' => array(
    'type' => 'string',
    'null' => true,
    'length' => 140
   ),
   'title' => array(
    'type' => 'string',
    'null' => true,
    'length' => 255
   ),
   'subtitle' => array(
    'type' => 'string',
    'null' => true,
    'length' => 255
   ),
   'body' => array(
    'type' => 'text',
    'null' => true,
   ),
   'date' => array(
    'type' => 'date',
    'null' => true,
   ),
  )
 );

  public function listSources() {
  return array('apps');
 }

  public function describe($model) {
  return $this->_schema['apps'];
 }

  function calculate(&$model, $func, $params = array()) {
   return '__'.$func;
  }

  function __getPage($items = null, $queryData = array()) {
  if (empty($queryData['limit']) ) {
   return $items;
  }
  $limit = $queryData['limit'];
  $page = $queryData['page'];
  $offset = $limit * ($page-1);
  return array_slice($items, $offset, $limit);
 }

  function __sortItems(&$model, $items, $order) {
  if ( empty($order) || empty($order[0]) ) {
   return $items;
  }

  $sorting = array();
  foreach( $order as $orderItem ) {
   if ( is_string($orderItem) ) {
    $field = $orderItem;
    $direction = 'asc';
   }
   else {
    foreach( $orderItem as $field => $direction ) {
     continue;
    }
   }

   $field = str_replace($model->alias.'.', '', $field);

   $values =  Set::extract($items, '{n}.'.$field);
   if ( in_array($field, array('lastBuildDate', 'pubDate')) ) {
    foreach($values as $i => $value) {
     $values[$i] = strtotime($value);
    }
   }
   $sorting[] = $values;

   switch(low($direction)) {
    case 'asc':
     $direction = SORT_ASC;
     break;
    case 'desc':
     $direction = SORT_DESC;
     break;
    default:
     trigger_error('Invalid sorting direction '. low($direction));
   }
   $sorting[] = $direction;
  }

  $sorting[] = &$items;
  $sorting[] = $direction;
  call_user_func_array('array_multisort', $sorting);

  return $items;
 }

  public function read($model, $queryData = array()) {
    $feedPath = 'xml/example.xml';
    $xml = new Xml($feedPath);
    $xml = $xml->toArray();
  foreach ($xml['Items']['Item'] as $record) {
    $record = array('App' => $record);
    $results[] = $record;
  }
    $results = $this->__getPage($results, $queryData);
    //Return item count
    if (Set::extract($queryData, 'fields') == '__count' ) {
     return array(array($model->alias => array('count' => count($results))));
    }
    return $results;
 }
}
?>

Основная структура XML:

<items>
 <item id="1">
   <type>Type</type>
   <title>Title</title>
   <subtitle>Subtitle</subtitle>
   <date>15-12-2010</date>
   <body>Body text</body>
 </item>
</items>

Редактировать:

Должен был прочитать руководство более внимательно:

И это в значительной степени все, что есть к этому. Соединяя эту DataSource к модели, вы тогда сможете использовать модель :: Найти () / Сохранить (), как вы обычно, и соответствующие данные и / или параметры, используемые для вызова этих методов, будут передаваться самой данных , где вы можете решить реализовать любые необходимые вам функции (например, модель :: Найти такие параметры, как «Условия», «ограничение» или даже ваши собственные пользовательские параметры).

Это было полезно?

Решение

Я подозреваю, что вам придется шоу Торт Как найти соседей, определяя метод в источниках данных.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top