• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Feeds. использование и создание плагинов. Feeds API
 

Feeds. использование и создание плагинов. Feeds API

on

  • 4,737 views

 

Statistics

Views

Total Views
4,737
Views on SlideShare
353
Embed Views
4,384

Actions

Likes
0
Downloads
0
Comments
0

14 Embeds 4,384

http://sanchiz.net 3686
http://sanchiz.dev 477
http://feeds.feedburner.com 80
http://sanchiz.host 55
http://95.85.41.221 32
http://188.120.253.37 28
http://cloud.feedly.com 9
http://supersay.ru 6
http://www.linkedin.com 6
http://nserver.be 1
http://qwe.sanchiz.net 1
http://localhost 1
http://digg.com 1
http://hghltd.yandex.net 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Feeds. использование и создание плагинов. Feeds API Feeds. использование и создание плагинов. Feeds API Presentation 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.module function 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.inc class 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.inc public 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.inc public 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.inc class 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_plugins hook_feeds_after_parse hook_feeds_presave hook_feeds_after_import hook_feeds_after_clear hook_feeds_parser_sources_alter hook_feeds_processor_targets_alter
    • Спасибо за внимание! Email: alexander.schedrov@gmail.com Twitter: @alexschedrov FB: schedrov http://sanchiz.net