Novas APIs no Drupal 7

     José San Martin
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

DrupalCamp Foz - Novas APIs Drupal 7