SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Documentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizDocumentacion edderson callpa_ortiz
Documentacion edderson callpa_ortiz
Edderson J. Ortiz
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
zfconfua
 
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
Johannes Hoppe
 
2014 it - app dev series - 03 - interagire con il database
2014   it - app dev series - 03 - interagire con il database2014   it - app dev series - 03 - interagire con il database
2014 it - app dev series - 03 - interagire con il database
MongoDB
 
Drupal Cms Prezentace
Drupal Cms PrezentaceDrupal Cms Prezentace
Drupal Cms Prezentace
Tomáš Kafka
 
Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3
Ying-Hsiang Liao
 

Tendances (20)

Documentacion edderson callpa_ortiz
Documentacion edderson callpa_ortizDocumentacion edderson callpa_ortiz
Documentacion edderson callpa_ortiz
 
With enter
With enterWith enter
With enter
 
Javascript and jQuery for Mobile
Javascript and jQuery for MobileJavascript and jQuery for Mobile
Javascript and jQuery for Mobile
 
Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0Юнит тестирование в Zend Framework 2.0
Юнит тестирование в Zend Framework 2.0
 
Miniray.php
Miniray.phpMiniray.php
Miniray.php
 
Index1
Index1Index1
Index1
 
Analizador sintáctico de Pascal escrito en Bison
Analizador sintáctico de Pascal escrito en BisonAnalizador sintáctico de Pascal escrito en Bison
Analizador sintáctico de Pascal escrito en Bison
 
Dwr实战
Dwr实战Dwr实战
Dwr实战
 
Iteratory
IteratoryIteratory
Iteratory
 
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
2012-10-12 - NoSQL in .NET - mit Redis und Mongodb
 
2014 it - app dev series - 03 - interagire con il database
2014   it - app dev series - 03 - interagire con il database2014   it - app dev series - 03 - interagire con il database
2014 it - app dev series - 03 - interagire con il database
 
Local storages
Local storagesLocal storages
Local storages
 
Jquery2
Jquery2Jquery2
Jquery2
 
Drupal Cms Prezentace
Drupal Cms PrezentaceDrupal Cms Prezentace
Drupal Cms Prezentace
 
Aller plus loin avec Doctrine2
Aller plus loin avec Doctrine2Aller plus loin avec Doctrine2
Aller plus loin avec Doctrine2
 
Wek14 mysql 2
Wek14 mysql 2Wek14 mysql 2
Wek14 mysql 2
 
アプリ設定の保存をシンプルに
アプリ設定の保存をシンプルにアプリ設定の保存をシンプルに
アプリ設定の保存をシンプルに
 
Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3Handbook - From jQuery to YUI 3
Handbook - From jQuery to YUI 3
 
Introducción a Bolt
Introducción a BoltIntroducción a Bolt
Introducción a Bolt
 
L’enfer des callbacks
L’enfer des callbacksL’enfer des callbacks
L’enfer des callbacks
 

En vedette

OpenY: Scaling and Sharing with Custom Drupal Distribution
OpenY: Scaling and Sharing with Custom Drupal DistributionOpenY: Scaling and Sharing with Custom Drupal Distribution
OpenY: Scaling and Sharing with Custom Drupal Distribution
DrupalCamp Kyiv
 

En vedette (9)

Ansible is the simplest way to automate. SymfonyCafe, 2015
Ansible is the simplest way to automate. SymfonyCafe, 2015Ansible is the simplest way to automate. SymfonyCafe, 2015
Ansible is the simplest way to automate. SymfonyCafe, 2015
 
OpenY: Scaling and Sharing with Custom Drupal Distribution
OpenY: Scaling and Sharing with Custom Drupal DistributionOpenY: Scaling and Sharing with Custom Drupal Distribution
OpenY: Scaling and Sharing with Custom Drupal Distribution
 
Build your application in seconds and optimize workflow as much as you can us...
Build your application in seconds and optimize workflow as much as you can us...Build your application in seconds and optimize workflow as much as you can us...
Build your application in seconds and optimize workflow as much as you can us...
 
Scaling and sharing: Building custom drupal distributions for federated organ...
Scaling and sharing: Building custom drupal distributions for federated organ...Scaling and sharing: Building custom drupal distributions for federated organ...
Scaling and sharing: Building custom drupal distributions for federated organ...
 
Building, Collaborating and Scaling Drupal Distributions for Federated Organi...
Building, Collaborating and Scaling Drupal Distributions for Federated Organi...Building, Collaborating and Scaling Drupal Distributions for Federated Organi...
Building, Collaborating and Scaling Drupal Distributions for Federated Organi...
 
Drupal Training Days 2017 - Drupal 8 basic functions.
Drupal Training Days 2017 - Drupal 8 basic functions.Drupal Training Days 2017 - Drupal 8 basic functions.
Drupal Training Days 2017 - Drupal 8 basic functions.
 
Building mobile applications with DrupalGap
Building mobile applications with DrupalGapBuilding mobile applications with DrupalGap
Building mobile applications with DrupalGap
 
Getting Started with DrupalGap
Getting Started with DrupalGapGetting Started with DrupalGap
Getting Started with DrupalGap
 
Ansible is the simplest way to automate. MoldCamp, 2015
Ansible is the simplest way to automate. MoldCamp, 2015Ansible is the simplest way to automate. MoldCamp, 2015
Ansible is the simplest way to automate. MoldCamp, 2015
 

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

  • 2. Возможности модуля Feeds: ● Агрегация данных из разных источников ● Выполнение в фоновом режиме ● Обновление/добавление данных через определенные промежутки времени ● Feeds API ● Использование GUIDs для связи ● Расширение существуеющих плагинов ● Доступ для загрузки пользователям ● Экспорт/импорт клонирование импортеров Стандартный набор: ● RSS, CSV, OPML, Sitemap ● HTTP, File upload ● Node, Taxonomy term, User
  • 3.
  • 4.
  • 5. 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)
  • 6. getMappingTargets() - маппинг полей сущности setTargetElement(FeedsSource $source, $target_node, $target_element, $value) - установка значений сущности existingEntityId(FeedsSource $source, FeedsParserResult $result) - проверка на существование сущности FeedsFetcher: fetch(FeedsSource $source) clear(FeedsSource $source) importPeriod(FeedsSource $source)
  • 7. 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)
  • 8. 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'); }
  • 9. 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; }
  • 10. 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(); }
  • 11. 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', ); }
  • 12. 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; }
  • 13.
  • 14.
  • 15. 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 "";', ); }
  • 16. 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'); }
  • 17. 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); } }
  • 18.
  • 19. Полезные модули для Feeds: ● Feeds directory fetcher ● Feeds SQL ● Feeds XPath Parser ● Comment processor ● Feeds Tamper ● Location Feeds ● Ubercart Feeds ● Commerce Feeds ● Commerce Feeds multitype
  • 21. Спасибо за внимание! Email: alexander.schedrov@gmail.com Twitter: @alexschedrov FB: schedrov http://sanchiz.net