Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Feeds.
Использование и
создание плагинов.
Щедров Александр
Возможности модуля Feeds:
● Агрегация данных из разных источников
● Выполнение в фоновом режиме
● Обновление/добавление данных через
определенные промежутки времени
● Feeds API
● Использование GUIDs для связи
● Расширение существуеющих плагинов
● Доступ для загрузки пользователям
● Экспорт/импорт клонирование импортеров
Стандартный набор:
● RSS, CSV, OPML, Sitemap
● HTTP, File upload
● Node, Taxonomy term, User
Feeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds API
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;
}
Feeds. использование и создание плагинов. Feeds API
Feeds. использование и создание плагинов. Feeds API
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 API
Полезные модули для 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

More Related Content

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

  • 2. Возможности модуля Feeds: ● Агрегация данных из разных источников ● Выполнение в фоновом режиме ● Обновление/добавление данных через определенные промежутки времени ● Feeds API ● Использование GUIDs для связи ● Расширение существуеющих плагинов ● Доступ для загрузки пользователям ● Экспорт/импорт клонирование импортеров Стандартный набор: ● RSS, CSV, OPML, Sitemap ● HTTP, File upload ● Node, Taxonomy term, User
  • 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; }
  • 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); } }
  • 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