drupal para desenvolvedores avançados


ementa
Entidades e OOP no Drupal
-
Ajax Framework do Drupal
- Construindo Web Services com Drupal
Title
introdução A Entities
Até o drupal 6, nodes eram considerados a abstração básica
Fields
Versão
Tradução
Listas
Por que não tudo como nodes?
- Usuários, comentarios e taxonomias com Fields, tradução e versão?
o que são entities
A nova abstração básica do drupal
Empacotamento de fields/funcionalidades por bundles
O drupal core já nos da algumas entities
Node = Entity Type
- Article = Bundle
ENTITIES JA EXISTENTES
Uso de entity_load
Uso de entity_extract_id
LISTAS COM ENTITY FIELD
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'article')
->propertyCondition('status', 1)
->fieldCondition('field_news_types', 'value', 'spotlight', '=')
->fieldCondition('field_photo', 'fid', 'NULL', '!=')
->fieldOrderBy('field_photo', 'fid', 'DESC')
->range(0, 10)
->addMetaData('account', user_load(1)); // Run the query as user 1.
ITERANDO SOBRE O RESULTADO
$result = $query->execute();
if (isset($result['node'])) {
$news_items_nids = array_keys($result['node']);
$news_items = entity_load('node', $news_items_nids);
}
ENTITY METADATA WRAPPER
Classe fornecida pelo módulo Entity
Visa facilitar a manipulação de Entidades e Fields, através de getters e setters
Facilita a manipulação de fields com tradução e/ou valores referenciados
ANTES E DEPOIS
- Modo Antigo
-
$node->field_number[LANGUAGE_NONE][0]['value']
- Com wrappers
$node_wrapper->field_number->value();
- $node_wrapper->author->value()
CRIANDO UMA ENTITY
/**
* Implements hook_entity_info().
*/
function yourmodule_entity_info() {
return array(
'name_of_entity' => array(
'label' => t('Name of entity'),
'base table' => 'your_table',
'entity keys' => array(
'id' => 'your_tables_primary_key',
),
),
);
Properties
INTRODUÇÃO A CLASSES
-
Base Entity Class
http://tinyurl.com/lgrav8b
-
Entity Controller
http://tinyurl.com/l283nw3
- Default classes da EntityAPI
adicionando field na entity
Conceito de bundles
Fieldable
- Criar Field e Instancia
- field_create_field
- field_create_instance
- FieldAttach
- Anexe um conjunto de campos a um formulario
Interface administrativa
'admin ui' => array(
'path' => 'admin/structure/profiles',
'file' => 'profile2.admin.inc',
// OPTIONAL- See "Customize the User Interface" below if you set.
'controller class' => 'Profile2TypeUIController',
),
Entity operations
entity view modes
Introdução a View modes
View modes customizados
Método view()
ajax framework
Nova forma de fazer ajax no drupal
Baseado no ctoolsajax forms
-
Callbacks nos elementos
-
Escolhe qual elemento retornar
- Ajax submissions
- https://drupal.org/project/ajax_form_entity
ajax links
- use-ajax class
- path representa o callback
ajax callbacks
- Menu items e callbacks responsáveis por entrega de conteúdo dinâmico através do AJAX framework
- Ajax commands
- http://tinyurl.com/l72ealh
-
Performance: https://drupal.org/project/js
web services com drupal 7
Instalando o modulo services
o que é REST
- SOAP
- XLMRPC
- REST
resources
- user
- article
http Methods
http://www.restapitutorial.com/lessons/httpmethods.html
Create = PUT with a new URI POST to a base URI returning a newly created URI Read = GET Update = PUT with an existing URI
POST with existing endpoint, existing URI
Delete = DELETE
Interface Polymórfica, onde os métodos se aplicam à qualquer resource.
princípios do rest
- Interface uniforme
- Stateless
- Cacheável
- Client-Server
- Sistema em camadas
- Código on-demand
por que rest?
- Simples e light, comparado à protocolos como SOAP
- HTTP based
- Sugestivo - não rígido.
módulo services
- Entity based
criando um endpoint
- No Drupal, admin/structure/services/add entrando os seguintes valores:
- Nome de máquina do endpoint: rest
- Server: REST
- Path do endpoint: rest
- Session authentication: checked
- Click Save
- Click the Edit Resources link, na linha do novo Service na tabela
- Check: create, retrieve, update, delete and index under comment, node, taxonomy_term, taxonomy_vocabulary and user
- Check o box para connect under system
- Check os boxes para login, logout e register under user
- Click Save
- Click the Server tab
- Em Response formatters, check o box para json
- Em Request parsing, check os boxes para application/json, application/x-www-form-urlencoded, multipart/form-data
- Click Save
- Em admin/config/development/performance limpes po cache
testando resources
- cURL
- hURL
- Postman
COM CURL
com HUrl
Postman
utilizando parametros e argumentos com resources
hook_services_resources'operations' => array( 'update' => array( 'help' => 'Creates/updates a Technical support.', 'callback' => '_technical_support_update', 'access arguments' => array('update technical support through services'), 'args' => array( array( 'name' => 'partner_crm_id', 'type' => 'int', 'description' => 'The unique identifier for this partner in the CRM of Intelbras.', 'source' => array('path' => 0), 'default value' => NULL, 'optional' => FALSE, ), array( 'name' => 'data', 'type' => 'struct', 'description' => 'The data object', 'source' => 'data', 'optional' => FALSE, ), ), ),
alterando o response object
hook_rest_server_response_formatters_alter
http://tinyurl.com/nbzz9tg
functioncustom_services_resource_rest_server_response_formatters_alter(&$formatters) { //This will change the formatter for xml, to use our custom one so it renders correctly $formatters['xml']['view'] = 'ExampleRESTServerView'; } class ExampleRESTServerView extends RESTServerView { public function render() { $doc = new DOMDocument('1.0', 'utf-8'); $root = $doc->createElement('Fruit_Basket'); $doc->appendChild($root); $this->xml_recurse($doc, $root, $this->model); return $doc->saveXML(); }
services com requests autenticados
Services e contrib modules fornecem 3 tipos de autenticação
- Login com CSRF token
- Basic HTTP authentication
- API Key
- Oauth
login com CSRF token
Basic http auth
https://drupal.org/project/services_basic_auth
- Mais simples que CSFR
- Usa login & password do usuário Drupal, enviado em HTTP headers
- Não é seguro
api key
Permite a utilização de uma chave que representará um usuário no endpoint.
https://drupal.org/project/services_api_key_auth
- Mais simples
- Configurável por usuário, por endpoint
views com services
https://drupal.org/project/services_views
- Permite que uma view seja um resource
- Possibilita o output de qualquer view por services
- Suporte a
- Filtros expostos
- offset
- limites
- formato de output
services com views filters
custom services resource
Implementação de alguns hooks e callbacks:
- hook_ctools_plugin_api
- registra seu services plugin
- hook_services_resources
- registra seu resource com services
- access callback
- output callback
www.drupalgap.org/node/187
drupal para desenvolvedores avançados
By Vinicius Freitas
drupal para desenvolvedores avançados
- 1,126