SlideShare a Scribd company logo
Novas APIs no Drupal 7

     José San Martin
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
Database Layer
Banco de dados

• “Query builders” paraconsultas INSERT,
  UPDATE, DELETE, MERGE, e SELECT.
• Suporteparareplicação master/slave,
  transações, consultas multi-insert,delayed
  inserts, entre outros.
• Suporte a SQLite.
• Uso do engine InnoDBporpadrão, aoinvés
  de MyISAM, emMySQL, quandodisponível
Database layer

• Camada de abstração
• Permiteouso com diversosservidores de
  BD
• Baseadonabiblioteca PDO do PHP
• FunçõesespeciaisparaconstruirSELECTs,
  INSERTs, UPDATEs, DELETEseMERGEs
select com db_query

Drupal 6:
$query = db_query('SELECT title FROM {node}');

while ($n = db_fetch_object($query)) {
  $titles[] = $n->title;
}
select com db_query

Drupal 7:
$results = db_query('SELECT title FROM
  {node}');

foreach($results as $n) {
  $titles[] = $n->title;
}
select com db_query

Drupal 6:
$query = db_query('
   SELECT title FROM {node}
   WHERE uid = %d', 1);
select com db_query

Drupal 7:
$results = db_query(
   'SELECT title FROM {node}
    WHERE uid = :uid’,
array(':uid' => 1)
);

foreach($results as $n) {
  $titles[] = $n->title;
}
select com db_query

Drupal 7:
$results = db_query(
   'SELECT title FROM {node}
    WHERE title = :title',
array(':title' => 'Foz')
);

foreach($results as $n) {
  $titles[] = $n->title;
}
select com db_query

Drupal 7:
$results = db_query(
   'SELECT title FROM {node}
    WHERE title LIKE :title',
array(':title' => 'Foz%')
);

foreach($results as $n) {
  $titles[] = $n->title;
}
query objects

• abstraçãoparadescreverumaconsultaaoba
  nco de dados
• Passos:
  – Crie a query (db_select, db_insert, db_delete)
  – Adicionecamposoucondições
  – ->execute();
insert

Drupal 6:
$query = db_query(
   "INSERT INTO {role}
    (name, weight)
    VALUES ('%s', %d)",
   'Admin', -10
);
insert

Drupal 7:
$fields = array(
   'name' => 'Admin’,
   'weight' => 0,
);

db_insert('role')->fields($fields)->execute();



            O método execute() vairetornaro campo auto_increment
            (nessecaso, rid)
ouusando a API do Drupal…

Drupal 6 eDrupal 7:
$fields = array(
   'name' => 'Admin’,
   'weight' => 0,
);

drupal_write_record('role', $fields);
multi-insert
$values = array(
   array(
      'title' => 'Example',
      'uid' => 1,
      'created' => REQUEST_TIME,
   ),
   array(
      'title' => 'Example 2',
      'uid' => 1,
      'created' => REQUEST_TIME,
   ),
);
multi-insert
$query = db_insert('node')->fields(
array('title', 'uid', 'created')
);

foreach ($values as $record) {
  $query->values($record);
}
$query->execute();


           O método execute() nãovairetornar nada
db_delete
$num_deleted = db_delete('node')
  ->condition('nid', 5)
  ->execute();




           O método execute() vairetornar a quantidade de linhasapagadas
db_select
$results = db_select('node', 'n')
  ->fields('n', array('title'))
  ->condition('n.uid', 0, '<>')
  ->execute();

foreach ($results as $n) {
  $titles[] = $n->title;
}
conditions
->condition('n.uid', 0, '=')
->condition('n.uid', 0) //igual a linhaacima
->condition('n.uid', 0, '<>')
->condition('n.nid', 300, '>=')
->condition('n.uid', array(1,2,3), 'IN')
->condition('n.title', db_like($st).'%',
  'LIKE')
->condition('n.nid', array(10,20), 'BETWEEN')
->isNull('nomedocampo')
->isNotNull('nomedocampo')
db_select: joins
$query = db_select('node', 'n')
  ->fields('n', array('title'))
  ->condition('n.uid', 0, '<>');

$alias = $query->join('users', 'u', 'n.uid =
  u.uid');

$results = $query->fields('u', array('name'))
                  ->execute();
db_selectoudb_query?

• db_queryémaiseficiente
• db_selectémaisabstratoepermitequery_alt
  er
hook_query_alter

• Permitealteraruma query
  definidaporoutromódulo
• Baseia-se na tag da $query
hook_query_alter
$query->addTag('node_access');

function
  mymodule_query_alter(QueryAlterableInterface$
  query) {

    if ($query->hasTag('nomedatag')) {
      $query->range(0, 2);
      $query->range(0, 2);
    }
}
Files API
Novidades

• Arquivospassam a ser cidadãos de
  primeiraclasse, ouseja, entidades
• Stream wrappers
• Managed Files vs. Unmanaged Files
  – tabelafiles_managed
  – funçõesfile_unmanaged_* paratodas as
    operaçõesquenãosalvem dados natabela
Stream Wrappers

• ProvidospeloDrupal
  – public://arquivo.txt
  – private://outro-arquivo.txt
  – temporary://mais-um-arquivo.txt
• Providospormóduloscustomizados:
  – youtube://NIfl2o44zb0
copiar um arquivo
$file = file_load(1);   // fid

if (file_prepare_directory("public://pasta") {
  $copia =
file_copy($file, 'public://pasta/arq.jpg');


 // $copiaestásalvanatabelafile_managed

delete_file($copia);
}
exibir a url
$file = file_load(1);

print $file->uri; // public://file.png

$url = file_create_url($file->uri);

print $url;
//
   http://localhost/foz/sites/default/files/file
maisinformações: drupal.org/developing/api




José San Martin
jose@chuva-inc.com
http://chuva-inc.com.br

More Related Content

What's hot (20)

ZIP
What's new in the Drupal 7 API?
Alexandru Badiu
 
PDF
Drupal - dbtng 25th Anniversary Edition
ddiers
 
KEY
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Hiroshi Shibamura
 
PDF
Drush. Secrets come out.
Alex S
 
PDF
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
PDF
The Origin of Lithium
Nate Abele
 
PDF
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
PDF
Future of HTTP in CakePHP
markstory
 
PDF
PHP Data Objects
Wez Furlong
 
PDF
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
PDF
CakeFest 2013 keynote
José Lorenzo Rodríguez Urdaneta
 
PDF
Doctrine 2
zfconfua
 
KEY
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
PDF
Database API, your new friend
kikoalonsob
 
KEY
Php 101: PDO
Jeremy Kendall
 
PDF
New in cakephp3
markstory
 
PDF
Dependency Injection
Rifat Nabi
 
PDF
Dependency Injection IPC 201
Fabien Potencier
 
PDF
Things I Believe Now That I'm Old
Ross Tuck
 
PDF
The State of Lithium
Nate Abele
 
What's new in the Drupal 7 API?
Alexandru Badiu
 
Drupal - dbtng 25th Anniversary Edition
ddiers
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Hiroshi Shibamura
 
Drush. Secrets come out.
Alex S
 
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
The Origin of Lithium
Nate Abele
 
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
Future of HTTP in CakePHP
markstory
 
PHP Data Objects
Wez Furlong
 
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
CakeFest 2013 keynote
José Lorenzo Rodríguez Urdaneta
 
Doctrine 2
zfconfua
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
Database API, your new friend
kikoalonsob
 
Php 101: PDO
Jeremy Kendall
 
New in cakephp3
markstory
 
Dependency Injection
Rifat Nabi
 
Dependency Injection IPC 201
Fabien Potencier
 
Things I Believe Now That I'm Old
Ross Tuck
 
The State of Lithium
Nate Abele
 

Similar to DrupalCamp Foz - Novas APIs Drupal 7 (15)

PPTX
Drupal II: The SQL
ddiers
 
PPTX
Drupal7 dbtng
Nicolas Leroy
 
PDF
Drupal 7 database api
Andrii Podanenko
 
PDF
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
camp_drupal_ua
 
ODP
PHP com MongoDB
Lucas de Oliveira
 
PDF
Doctrine Project
Daniel Lima
 
ODP
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
PPTX
MongoDB & Drupal
Паша Павел
 
KEY
Object Relational Mapping in PHP
Rob Knight
 
PDF
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 
ODP
This upload requires better support for ODP format
Forest Mars
 
ODP
Beyond php - it's not (just) about the code
Wim Godden
 
PDF
New in Drupal7
swapna46
 
PPT
Crash Course to SQL in PHP
webhostingguy
 
ODP
Beyond php it's not (just) about the code
Wim Godden
 
Drupal II: The SQL
ddiers
 
Drupal7 dbtng
Nicolas Leroy
 
Drupal 7 database api
Andrii Podanenko
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
camp_drupal_ua
 
PHP com MongoDB
Lucas de Oliveira
 
Doctrine Project
Daniel Lima
 
DrupalCon Chicago Practical MongoDB and Drupal
Doug Green
 
MongoDB & Drupal
Паша Павел
 
Object Relational Mapping in PHP
Rob Knight
 
Doctrine MongoDB ODM (PDXPHP)
Kris Wallsmith
 
This upload requires better support for ODP format
Forest Mars
 
Beyond php - it's not (just) about the code
Wim Godden
 
New in Drupal7
swapna46
 
Crash Course to SQL in PHP
webhostingguy
 
Beyond php it's not (just) about the code
Wim Godden
 
Ad

Recently uploaded (20)

PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
Ad

DrupalCamp Foz - Novas APIs Drupal 7