feeds. использование и создание плагинов. feeds api
DESCRIPTION
TRANSCRIPT
Feeds.Использование и
создание плагинов.
Щедров Александр
Возможности модуля Feeds:● Агрегация данных из разных источников● Выполнение в фоновом режиме● Обновление/добавление данных через
определенные промежутки времени● Feeds API● Использование GUIDs для связи● Расширение существуеющих плагинов● Доступ для загрузки пользователям● Экспорт/импорт клонирование импортеровСтандартный набор:● RSS, CSV, OPML, Sitemap● HTTP, File upload● Node, Taxonomy term, User
FeedsProcessor:
entityType() - должен возвращать тип сущности
entityInfo() - определение доп. информации сущности
newEntity(FeedsSource $source) - инициализация новой сущности
entityLoad(FeedsSource $source, $entity_id) - загрузка сущности,
если существует с указанным уникальным ключом
entitySave($entity)
entityValidate($entity)
entitySaveAccess($entity)
entityDeleteMultiple($entity_ids)
process(FeedsSource $source, FeedsParserResult $parser_result)
getMappingTargets() - маппинг полей сущности
setTargetElement(FeedsSource $source, $target_node,
$target_element, $value) - установка значений сущности
existingEntityId(FeedsSource $source, FeedsParserResult $result) -
проверка на существование сущности
FeedsFetcher:
fetch(FeedsSource $source)
clear(FeedsSource $source)
importPeriod(FeedsSource $source)
FeedsParser:
parse(FeedsSource $source, FeedsFetcherResult $fetcher_result)
getMappingSources()
getSourceElement(FeedsSource $source, FeedsParserResult $result,
$element_key)
clear(FeedsSource $source)
Общие методы:
configDefaults(), sourceDefaults()
configForm(&$form_state), sourceForm($source_config)
configFormValidate(&$values), sourceFormValidate(&$values)
configFormSubmit(&$values), sourceFormSubmit(&$values)
json_example_parser.modulefunction json_example_parser_feeds_plugins() { $info = array(); $info['JsonExampleParser'] = array( 'name' => 'JSON parser', 'description' => 'Parses custom JSON.', 'handler' => array( 'parent' => 'FeedsParser', // родительский класс от которого наследуем парсер, стандартные классы Feeds - FeedsFetcher, FeedsParser и FeedsProcessor 'class' => 'JsonExampleParser', // название парсера, должно совпадать с ключем в массиве 'file' => 'JsonExampleParser.inc', // файл класса парсера 'path' => drupal_get_path('module', 'json_example_parser'), // путь к классу парсера ), ); return $info;}
function json_example_parser_enable() { //clear the cache to display in Feeds as available plugin. cache_clear_all('plugins:feeds:plugins', 'cache');}
JsonExampleParser.incclass JsonExampleParser extends FeedsParser { public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) { $result = new FeedsParserResult(); //$source_config = $source->getConfigFor($this); $source_config = $this->config; $fetch_items = json_decode($fetcher_result->getRaw()); foreach ($fetch_items as $value) { $item = array('name' => $value->name); if ($value->year) { $item['year'] = intval($value->year); } if ($value->price) { $item['price'] = floatval($value->price); } if ( $source_config['type'] == 'all' || ($source_config['type'] == 'free' && $item['price'] == 0) || ($source_config['type'] == 'paid' && $item['price'] > 0)) { $result->items[] = $item; } } return $result; }
JsonExampleParser.incpublic function getMappingSources() { return array( 'name' => array( 'name' => t('Game name'), 'description' => t('The name of the computer game.'), ), 'year' => array( 'name' => t('Release year'), 'description' => t('Release year of the computer game.'), ), 'price' => array( 'name' => t('Game price'), 'description' => t('The cost of the computer game.'), ), ) + parent::getMappingSources(); }
JsonExampleParser.inc public function configForm(&$form_state) { $form = array(); $form['type'] = array( '#type' => 'select', '#title' => t('Game type'), '#description' => t('Game filter by type.'), '#options' => array( 'all' => t('All game'), 'paid' => t('Paid'), 'free' => t('Free'), ), '#default_value' => $this->config['type'], ); return $form; }
public function configDefaults() { return array( 'type' => 'all', ); }
JsonExampleParser.incpublic function sourceDefaults() { return array( 'type' => $this->config['type'], ); } public function sourceForm($source_config) { $form = array(); $form['#weight'] = -10; $form['type'] = array( '#type' => 'select', '#title' => t('Game type'), '#description' => t('Game filter by type.'), '#options' => array( 'all' => t('All game'), 'paid' => t('Paid'), 'free' => t('Free'), ), '#default_value' => isset($source_config['type']) ? $source_config['type'] : 'all', ); return $form; }
PhpExampleFetcher.incclass PhpExampleFetcher extends FeedsFetcher { function configForm(&$form_state) { $form = array(); $form['php_code'] = array( '#type' => 'textarea', '#title' => t('Fetching PHP code'), '#default_value' => $this -> config['php_code'], ); $form['validate_button'] = array( '#type' => 'button', '#value' => t('Validate') ); return $form; } function configDefaults() { return array('php_code' => 'return "";', ); }
PhpExampleFetcher.inc function configFormValidate(&$data) { $code = $data['php_code']; if (strpos(trim($code), '<?') === 0) { form_set_error("php_code", t("You should not include PHP starting tags")); } if (!isset($data['op']) || $data['op'] != t('Validate')) { return; } $eval = eval($code); if ($eval === FALSE) { form_set_error("php_code", t("Parse error or your code returned FALSE.")); } elseif (!is_string($eval)) { form_set_error("php_code", t("Your code MUST return STRING")); } else { drupal_set_message(t("Your code looks OK. It returned:") . "<br/>" . nl2br(htmlentities($eval)), 'status'); } drupal_set_message(t('Your changes were NOT saved.'), 'warning'); }
}
PhpExampleFetcher.inc function fetch(FeedsSource $source) { $config = $this->getConfig(); $script = $config['php_code']; $eval = eval($script); if ($eval === FALSE) { throw new Exception("Parse error. PHP Fetcher code is invalid."); } return new FeedsFetcherResult($eval); }}
Полезные модули для Feeds:● Feeds directory fetcher● Feeds SQL● Feeds XPath Parser● Comment processor● Feeds Tamper● Location Feeds● Ubercart Feeds● Commerce Feeds● Commerce Feeds multitype
hooks
hook_feeds_pluginshook_feeds_after_parsehook_feeds_presavehook_feeds_after_importhook_feeds_after_clearhook_feeds_parser_sources_alterhook_feeds_processor_targets_alter
Спасибо за внимание!
Email: [email protected]: @alexschedrovFB: schedrovhttp://sanchiz.net