SlideShare une entreprise Scribd logo
1  sur  29
THE DRUPAL 7 API
     Badiu Alexandru




    Drupalcamp Bucharest 2011
D7 API
•   New stuff in the Drupal 7 API
•   Things that have changed since D6
•   Not gonna cover all
•   Just what I found interesting



             Drupalcamp Bucharest 2011
D7 API
•   Database API
•   Translation API
•   Render Arrays
•   Drupal Queues
•   File API


               Drupalcamp Bucharest 2011
DATABASE
•   Completly rewritten
•   Object oriented
•   Easier to hook into queries
•   Easier to support multiple db servers
•   Vendor agnostic


             Drupalcamp Bucharest 2011
DATABASE
db_affected_rows(), db_distinct_field(),
db_error(), db_last_insert_id(),
db_placeholders(), db_lock_table(),
db_prefix_tables(), db_result(), db_fetch_*(),
db_version(), db_rewrite_sql(),
hook_db_rewrite_sql(), pager_query(),
tablesort_sql() etc are gone.



            Drupalcamp Bucharest 2011
DATABASE
   •   SELECT
// Drupal 6
$result = db_query("SELECT nid, title FROM {node} WHERE uid
= %d AND type IN (" . db_placeholders(array('page',
'story'), 'varchar') . ")", 5, 'page', 'story');

// Drupal 7
$result = db_query("SELECT nid, title FROM {node} WHERE uid
= :uid AND type IN (:type)", array(
  ':uid' => 5,
  ':type' => array('page', 'story'),
));


                   Drupalcamp Bucharest 2011
DATABASE
   •   Getting results
// Drupal 6
while ($record = db_fetch_object($result)) {
  // Do stuff with $record, which is an object
}


// Drupal 7
foreach ($result as $record) {
  // Do stuff with $record, which is an object
}




                   Drupalcamp Bucharest 2011
DATABASE
   •   INSERT
// Drupal 6
db_query("INSERT INTO {mytable} (intvar, stringvar,
floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id();

// Drupal 7
$id = db_insert('mytable')
  ->fields(array(
    'intvar' => 5,
    'stringvar' => 'hello world',
    'floatvar' => 3.14,
  ))
  ->execute();



                        Drupalcamp Bucharest 2011
DATABASE
   •   UPDATE
// Drupal 6
db_query("UPDATE {node} SET title='%s', status=%d WHERE uid=
%d", 'hello world', 1, 5);


// Drupal 7
db_update('node')
  ->fields(array('title' => 'hello world', 'status' => 1))
  ->condition('uid', 5)
  ->execute();



                   Drupalcamp Bucharest 2011
DATABASE
   •   DELETE
// Drupal 6
db_query("DELETE FROM {node} WHERE uid=%d AND created < %d",
5, REQUEST_TIME - 3600);


// Drupal 7
db_delete('node')
  ->condition('uid', 5)
  ->condition('created', REQUEST_TIME - 3600, '<')
  ->execute();



                   Drupalcamp Bucharest 2011
DATABASE
   •   JOINS
SELECT fm.filename, fm.uri FROM file_usage AS fu
INNER JOIN file_managed AS fm
ON fu.fid = fm.fid
WHERE fu.id = 5;

$query = db_select('file_usage', 'fu');
$query->join('file_managed', 'fm', 'fu.fid = fm.fid'); // inner_join
file_usage table against file_managed
$query
   ->fields('fu', array('fid')) // specifying fields from file_usage table
   ->fields('fm', array('filename', 'uri')) // specifying fields from
file_managed table
   ->condition('fu.id', 5, '='); // specifying the condition where fu.id =
5
 
$result = $query->execute(); // executing the query once we finish building
the query object

                        Drupalcamp Bucharest 2011
DATABASE
•   Queries can have tags
•   hook_query_alter
•   hook_query_TAG_alter
•   Transactions



            Drupalcamp Bucharest 2011
DATABASE
•   $query->orderRandom()
•   $query->orderBy(“field”)
•   $query->orderBy(“field”)->orderRandom()
•   $query->groupBy()
•   $query->range(0, 20)
•   $query->countQuery()->execute()-
    >fetchField()

             Drupalcamp Bucharest 2011
TRANSLAT
•   The whole system has been
    improved
•   Localization server
•   Translations can be updated
•   Localization module (contrib)


             Drupalcamp Bucharest 2011
TRANSLAT
   •   Contexts
   •   Avoid Views vs 5 Views
   •   Does not work with Javascript
   •   Does not work with watchdog

$long_may = t('May', array(), array('context' => 'Long month name'));




                       Drupalcamp Bucharest 2011
RENDER
•   A page’s content is kept as an array
    until the last stage (theme layer)
•   A module can change the content at
    the very last minute
•   Instead of returning HTML you
    return an array


            Drupalcamp Bucharest 2011
RENDER
$page = array(
  '#show_messages' => TRUE,
  '#theme' => 'page',
  '#type' => 'page',
  'content' => array(
    'system_main' => array(...),
    'another_block' => array(...),
    '#sorted' => TRUE,
  ),
  'sidebar_first' => array(
    ...
  ),
  'footer' => array(
    ...
  ),
  ...
);


                        Drupalcamp Bucharest 2011
RENDER
  •   hook_page_alter
function mymodule_page_alter(&$page) {
  // Move search form into the footer.
  $page['footer']['search_form'] = $page['sidebar_first']
['search_form'];
  unset($page['sidebar_first']['search_form']);
 
  // Remove the "powered by Drupal" block
  unset($page['footer']['system_powered-by']);
}



                  Drupalcamp Bucharest 2011
RENDER
   •   Generating page output
return array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => 'A first paragraph',
  ),
  'second_para' => array(
    '#items' => array('first item', 'second item', 'third
item'),
    '#theme' => 'item_list',
  ),
);


                   Drupalcamp Bucharest 2011
RENDER
   •   hide()
<div class="content">
  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>
</div>

<?php print render($content['links']); ?>

<?php print render($content['comments']); ?>




                        Drupalcamp Bucharest 2011
DRUPAL
•   Stop doing lenghty operations on
    cron
•   Like: indexing Solr data, generating
    thumbnails
•   We have producers and workers
•   Backported to Drupal 6


              Drupalcamp Bucharest 2011
DRUPAL
•   Reliable queues
•   Unreliable queues
•   Pluggable backends
•   Add Beanstalk and Supervisord and
    you’re good to go



             Drupalcamp Bucharest 2011
DRUPAL
$queue = DrupalQueue::get('aggregator_feeds');
  foreach ($result as $feed) {
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than
once.
      db_update('aggregator_feed')
        ->fields(array('queued' => REQUEST_TIME))
        ->condition('fid', $feed->fid)
        ->execute();
    }
  }


                  Drupalcamp Bucharest 2011
DRUPAL
function aggregator_cron_queue_info() {
  $queues['aggregator_feeds'] = array(
     'worker callback' => 'aggregator_refresh',
     'time' => 60,
  );
  return $queues;
}




                  Drupalcamp Bucharest 2011
FILE API
•   Uses streams
•   public://file.txt
•   private://file.txt
•   temporary://file.txt
•   PHP’s provided: http://, ftp://
•   A module can create a new stream



               Drupalcamp Bucharest 2011
FILE API
•   No more public or private
•   Uses streams
•   public://file.txt, private://file.txt,
    temporary://file.txt




              Drupalcamp Bucharest 2011
FILE API
•   Managed and unmanaged files
•   file_copy / file_unmanaged_copy
•   PHP’s provided: http://, ftp://
•   A module can create a new stream



              Drupalcamp Bucharest 2011
FILE API
function file_example_stream_wrappers() {
  $wrappers = array(
     'session' => array(
        'name' => t('Example: $_SESSION variable storage'),
        'class' => 'FileExampleSessionStreamWrapper',
        'description' => t('Store files in the $_SESSION
variable as an example.'),
     ),
  );
  return $wrappers;
}




                   Drupalcamp Bucharest 2011
THANK
   andu@ctrlz.ro
   http://ctrlz.ro




Drupalcamp Bucharest 2011

Contenu connexe

Tendances

第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
Kaz Watanabe
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
waraiotoko
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
Kris Wallsmith
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias
 

Tendances (20)

CakeFest 2013 keynote
CakeFest 2013 keynoteCakeFest 2013 keynote
CakeFest 2013 keynote
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Drupal 7 database api
Drupal 7 database api Drupal 7 database api
Drupal 7 database api
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource第49回Php勉強会@関東 Datasource
第49回Php勉強会@関東 Datasource
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
PHP API
PHP APIPHP API
PHP API
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)Introducing Assetic (NYPHP)
Introducing Assetic (NYPHP)
 
Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Views notwithstanding
Views notwithstandingViews notwithstanding
Views notwithstanding
 

Similaire à What's new in the Drupal 7 API?

DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
camp_drupal_ua
 

Similaire à What's new in the Drupal 7 API? (20)

Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.x
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
Andriy Podanenko.Drupal database api.DrupalCamp Kyiv 2011
 
Fatc
FatcFatc
Fatc
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Debugging in drupal 8
Debugging in drupal 8Debugging in drupal 8
Debugging in drupal 8
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 

Plus de Alexandru Badiu

Plus de Alexandru Badiu (13)

Behavior Driven Development with Drupal
Behavior Driven Development with DrupalBehavior Driven Development with Drupal
Behavior Driven Development with Drupal
 
Drupal 8
Drupal 8Drupal 8
Drupal 8
 
Drupal as a first class mobile platform
Drupal as a first class mobile platformDrupal as a first class mobile platform
Drupal as a first class mobile platform
 
Cloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloudCloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloud
 
REST Drupal
REST DrupalREST Drupal
REST Drupal
 
Cloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloudCloud to the rescue? How I learned to stop worrying and love the cloud
Cloud to the rescue? How I learned to stop worrying and love the cloud
 
Using Features
Using FeaturesUsing Features
Using Features
 
Drupal, Android and iPhone
Drupal, Android and iPhoneDrupal, Android and iPhone
Drupal, Android and iPhone
 
Publish and Subscribe
Publish and SubscribePublish and Subscribe
Publish and Subscribe
 
Using Features
Using FeaturesUsing Features
Using Features
 
Concepte de programare functionala in Javascript
Concepte de programare functionala in JavascriptConcepte de programare functionala in Javascript
Concepte de programare functionala in Javascript
 
Drupal and Solr
Drupal and SolrDrupal and Solr
Drupal and Solr
 
Prezentare Wurbe
Prezentare WurbePrezentare Wurbe
Prezentare Wurbe
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

What's new in the Drupal 7 API?

  • 1. THE DRUPAL 7 API Badiu Alexandru Drupalcamp Bucharest 2011
  • 2. D7 API • New stuff in the Drupal 7 API • Things that have changed since D6 • Not gonna cover all • Just what I found interesting Drupalcamp Bucharest 2011
  • 3. D7 API • Database API • Translation API • Render Arrays • Drupal Queues • File API Drupalcamp Bucharest 2011
  • 4. DATABASE • Completly rewritten • Object oriented • Easier to hook into queries • Easier to support multiple db servers • Vendor agnostic Drupalcamp Bucharest 2011
  • 5. DATABASE db_affected_rows(), db_distinct_field(), db_error(), db_last_insert_id(), db_placeholders(), db_lock_table(), db_prefix_tables(), db_result(), db_fetch_*(), db_version(), db_rewrite_sql(), hook_db_rewrite_sql(), pager_query(), tablesort_sql() etc are gone. Drupalcamp Bucharest 2011
  • 6. DATABASE • SELECT // Drupal 6 $result = db_query("SELECT nid, title FROM {node} WHERE uid = %d AND type IN (" . db_placeholders(array('page', 'story'), 'varchar') . ")", 5, 'page', 'story'); // Drupal 7 $result = db_query("SELECT nid, title FROM {node} WHERE uid = :uid AND type IN (:type)", array(   ':uid' => 5,   ':type' => array('page', 'story'), )); Drupalcamp Bucharest 2011
  • 7. DATABASE • Getting results // Drupal 6 while ($record = db_fetch_object($result)) {   // Do stuff with $record, which is an object } // Drupal 7 foreach ($result as $record) {   // Do stuff with $record, which is an object } Drupalcamp Bucharest 2011
  • 8. DATABASE • INSERT // Drupal 6 db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14); $id = db_last_insert_id(); // Drupal 7 $id = db_insert('mytable')   ->fields(array(     'intvar' => 5,     'stringvar' => 'hello world',     'floatvar' => 3.14,   ))   ->execute(); Drupalcamp Bucharest 2011
  • 9. DATABASE • UPDATE // Drupal 6 db_query("UPDATE {node} SET title='%s', status=%d WHERE uid= %d", 'hello world', 1, 5); // Drupal 7 db_update('node')   ->fields(array('title' => 'hello world', 'status' => 1))   ->condition('uid', 5)   ->execute(); Drupalcamp Bucharest 2011
  • 10. DATABASE • DELETE // Drupal 6 db_query("DELETE FROM {node} WHERE uid=%d AND created < %d", 5, REQUEST_TIME - 3600); // Drupal 7 db_delete('node')   ->condition('uid', 5)   ->condition('created', REQUEST_TIME - 3600, '<')   ->execute(); Drupalcamp Bucharest 2011
  • 11. DATABASE • JOINS SELECT fm.filename, fm.uri FROM file_usage AS fu INNER JOIN file_managed AS fm ON fu.fid = fm.fid WHERE fu.id = 5; $query = db_select('file_usage', 'fu'); $query->join('file_managed', 'fm', 'fu.fid = fm.fid'); // inner_join file_usage table against file_managed $query ->fields('fu', array('fid')) // specifying fields from file_usage table ->fields('fm', array('filename', 'uri')) // specifying fields from file_managed table ->condition('fu.id', 5, '='); // specifying the condition where fu.id = 5   $result = $query->execute(); // executing the query once we finish building the query object Drupalcamp Bucharest 2011
  • 12. DATABASE • Queries can have tags • hook_query_alter • hook_query_TAG_alter • Transactions Drupalcamp Bucharest 2011
  • 13. DATABASE • $query->orderRandom() • $query->orderBy(“field”) • $query->orderBy(“field”)->orderRandom() • $query->groupBy() • $query->range(0, 20) • $query->countQuery()->execute()- >fetchField() Drupalcamp Bucharest 2011
  • 14. TRANSLAT • The whole system has been improved • Localization server • Translations can be updated • Localization module (contrib) Drupalcamp Bucharest 2011
  • 15. TRANSLAT • Contexts • Avoid Views vs 5 Views • Does not work with Javascript • Does not work with watchdog $long_may = t('May', array(), array('context' => 'Long month name')); Drupalcamp Bucharest 2011
  • 16. RENDER • A page’s content is kept as an array until the last stage (theme layer) • A module can change the content at the very last minute • Instead of returning HTML you return an array Drupalcamp Bucharest 2011
  • 17. RENDER $page = array(   '#show_messages' => TRUE,   '#theme' => 'page',   '#type' => 'page',   'content' => array(     'system_main' => array(...),     'another_block' => array(...),     '#sorted' => TRUE,   ),   'sidebar_first' => array(     ...   ),   'footer' => array(     ...   ),   ... ); Drupalcamp Bucharest 2011
  • 18. RENDER • hook_page_alter function mymodule_page_alter(&$page) {   // Move search form into the footer.   $page['footer']['search_form'] = $page['sidebar_first'] ['search_form'];   unset($page['sidebar_first']['search_form']);     // Remove the "powered by Drupal" block   unset($page['footer']['system_powered-by']); } Drupalcamp Bucharest 2011
  • 19. RENDER • Generating page output return array(   'first_para' => array(     '#type' => 'markup',     '#markup' => 'A first paragraph',   ),   'second_para' => array(     '#items' => array('first item', 'second item', 'third item'),     '#theme' => 'item_list',   ), ); Drupalcamp Bucharest 2011
  • 20. RENDER • hide() <div class="content">   <?php     // We hide the comments and links now so that we can render them later.     hide($content['comments']);     hide($content['links']);     print render($content);   ?> </div> <?php print render($content['links']); ?> <?php print render($content['comments']); ?> Drupalcamp Bucharest 2011
  • 21. DRUPAL • Stop doing lenghty operations on cron • Like: indexing Solr data, generating thumbnails • We have producers and workers • Backported to Drupal 6 Drupalcamp Bucharest 2011
  • 22. DRUPAL • Reliable queues • Unreliable queues • Pluggable backends • Add Beanstalk and Supervisord and you’re good to go Drupalcamp Bucharest 2011
  • 23. DRUPAL $queue = DrupalQueue::get('aggregator_feeds');   foreach ($result as $feed) {     if ($queue->createItem($feed)) {       // Add timestamp to avoid queueing item more than once.       db_update('aggregator_feed')         ->fields(array('queued' => REQUEST_TIME))         ->condition('fid', $feed->fid)         ->execute();     }   } Drupalcamp Bucharest 2011
  • 24. DRUPAL function aggregator_cron_queue_info() { $queues['aggregator_feeds'] = array( 'worker callback' => 'aggregator_refresh', 'time' => 60, ); return $queues; } Drupalcamp Bucharest 2011
  • 25. FILE API • Uses streams • public://file.txt • private://file.txt • temporary://file.txt • PHP’s provided: http://, ftp:// • A module can create a new stream Drupalcamp Bucharest 2011
  • 26. FILE API • No more public or private • Uses streams • public://file.txt, private://file.txt, temporary://file.txt Drupalcamp Bucharest 2011
  • 27. FILE API • Managed and unmanaged files • file_copy / file_unmanaged_copy • PHP’s provided: http://, ftp:// • A module can create a new stream Drupalcamp Bucharest 2011
  • 28. FILE API function file_example_stream_wrappers() { $wrappers = array( 'session' => array( 'name' => t('Example: $_SESSION variable storage'), 'class' => 'FileExampleSessionStreamWrapper', 'description' => t('Store files in the $_SESSION variable as an example.'), ), ); return $wrappers; } Drupalcamp Bucharest 2011
  • 29. THANK andu@ctrlz.ro http://ctrlz.ro Drupalcamp Bucharest 2011

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n