Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Drupal Design  Patterns       Erik Webb  Technical Consultant       Acquia, Inc.
Introduction• Technical Consultant at Acquia, Inc.• Best practices guru• Working with Drupal 3+ years• PHP programmer for ...
Agenda1. Creating your own hooks2. Effectively using static variables3. Utilizing Drupals cache4. Storing objects in the d...
These aren’t“design patterns”...      i know!
Creating Your Own           Hooks    “Hooks” by lovestruck.    http://www.flickr.com/photos/    lovestruck94/3329381854/5
Hook Types• Action• Aggregate• Alter               6
Using Hooks1. Simple invoking2. Aggregating results3. Altering data4. Passing by reference                     7
Simple Invoking<?php  // will call all modules   // implementing hook_hook_name  module_invoke_all(hook_name);?>          ...
Aggregate Results<?php  $result = array();  foreach (module_implements(hook_name) as$module) {    // will call all modules...
Altering Data<?php  $data = array(    key1 => value1,    key2 => value2,  );  // will call all modules   // implementing h...
Passing by Reference<?php  // @see user_module_invoke()  foreach (module_implements(hook_name) as $module) {    $function ...
Effectively using        static variables     “Time for Mommy to Windex those glass tank     walls” by Ninithedreamer.    ...
Static Variables• Not Drupal-specific (PHP feature)• Prevent duplicate work within a  request• Used in often-called functio...
Simple PHP Method<?php  function i_get_called_way_too_much() {    static $static_var;    if (!isset($static_var)) {      /...
Drupal 7 Method<?php  function i_get_called_way_too_much() {    $var = &drupal_static(__FUNCTION__);    if (!isset($var)) ...
Utilizing Drupals              cache     “Hello, I m Johny Cash comic book” by Bascom     Hogue.     http://www.flickr.com/...
Caching system• Prevent duplicate work between  requests• Used in complicated or remote  functions• Further benefits using ...
Cache Expirationcache_set($cid, $data, $bin = cache, $expire = CACHE_PERMANENT)     • CACHE_PERMANENT     • CACHE_TEMPORAR...
Usage Example<?php  $value = cache_get(cache_key);  if (FALSE == $value) {    // generate $value    cache_set(cache_key, $...
Create Your Own Cache<?php  /* @file my_module.install */  function my_module_schema() {    $schema[cache_my_cache] =     ...
Storing objects in          the database     “146/365 square peg into a round hole” by     rosipaw.     http://www.flickr.c...
Saving Objects• drupal_write_record()• Single statements INSERT/UPDATE• Use with new $fetchStyle in D7 or  db_fetch_object...
Schema Example<?php  // use the following table schema  $schema[my_table] = array(    description => My table.,    fields ...
Example<?php  $my_data = new stdClass();  $my_data->id = 1;    // remove this to see INSERT behavior  $my_data->value = so...
Serializing Objects• Automatically done in Schema API • Set ‘serialize’ property in field• Uses PHP serialize() and unseria...
Advanced             Schema Example<?php  // use the following table schema  $schema[my_table] = array(    description => ...
Example<?php  $my_data = new stdClass();  $my_data->id = 1;    // remove this to see INSERT behavior  $my_data->value = so...
Making the most of            menus     “271/365 Run Rabbit, Run Rabbit...” by sosij.     http://www.flickr.com/photos/shar...
Arguments• Title• Page• Access• Load               29
Title Arguments• Use with t() or custom callback• Dynamic titles from URL                   30
Page Arguments      31
Access Arguments       32
Load Arguments      33
Queueing/BatchingLocking mechanisms                     Registry alters        More tricks...                          Ren...
Further reading and  code snippets athttp://erikwebb.net/blog/drupal-design-      patterns
Questions?   @erikwebbwww.erikwebb.net
Drupal Design Patterns
Drupal Design Patterns
Drupal Design Patterns
Drupal Design Patterns
Upcoming SlideShare
Loading in …5
×

Drupal Design Patterns

10,945 views

Published on

Drupal's code involves many common coding techniques that make your code more readable, maintainable, and efficient. Although there are countless PHP tricks that could be used, I will focus on helper functions and other common methods used specifically by Drupal developers when writing good code.

Published in: Technology
  • Be the first to comment

Drupal Design Patterns

  1. 1. Drupal Design Patterns Erik Webb Technical Consultant Acquia, Inc.
  2. 2. Introduction• Technical Consultant at Acquia, Inc.• Best practices guru• Working with Drupal 3+ years• PHP programmer for 10+ years• Linux sysadmin for 6+ years 2
  3. 3. Agenda1. Creating your own hooks2. Effectively using static variables3. Utilizing Drupals cache4. Storing objects in the database5. Making the most of menus 3
  4. 4. These aren’t“design patterns”... i know!
  5. 5. Creating Your Own Hooks “Hooks” by lovestruck. http://www.flickr.com/photos/ lovestruck94/3329381854/5
  6. 6. Hook Types• Action• Aggregate• Alter 6
  7. 7. Using Hooks1. Simple invoking2. Aggregating results3. Altering data4. Passing by reference 7
  8. 8. Simple Invoking<?php  // will call all modules // implementing hook_hook_name  module_invoke_all(hook_name);?> 8
  9. 9. Aggregate Results<?php  $result = array();  foreach (module_implements(hook_name) as$module) {    // will call all modules implementing // hook_hook_name and    // push the results onto the $result array    $result[] = module_invoke(hook_name);  }?> 9
  10. 10. Altering Data<?php  $data = array(    key1 => value1,    key2 => value2,  );  // will call all modules // implementing hook_my_data_alter  drupal_alter(my_data, $data);?> 10
  11. 11. Passing by Reference<?php  // @see user_module_invoke()  foreach (module_implements(hook_name) as $module) {    $function = $module . _hook_name;    // will call all modules implementing hook_hook_name    // and can pass each argument as reference determined    // by the function declaration    $function($arg1, $arg2);  }?> 11
  12. 12. Effectively using static variables “Time for Mommy to Windex those glass tank walls” by Ninithedreamer. http://www.flickr.com/photos/ ninithedreamer/4682877279/12
  13. 13. Static Variables• Not Drupal-specific (PHP feature)• Prevent duplicate work within a request• Used in often-called functions 13
  14. 14. Simple PHP Method<?php  function i_get_called_way_too_much() {    static $static_var;    if (!isset($static_var)) {      // generate contents of static variable      $static_var = some value;    }    return $static_var;  }?> 14
  15. 15. Drupal 7 Method<?php  function i_get_called_way_too_much() {    $var = &drupal_static(__FUNCTION__);    if (!isset($var)) {      // generate contents of static variable      $var = some value;    }    return $var;  }  // allows for static variables to be reset // from another function  drupal_static_reset(i_get_called_way_too_much);?> 15
  16. 16. Utilizing Drupals cache “Hello, I m Johny Cash comic book” by Bascom Hogue. http://www.flickr.com/photos/christophererin/ 4873831108/16
  17. 17. Caching system• Prevent duplicate work between requests• Used in complicated or remote functions• Further benefits using distributed cache• Only ephemeral data 17
  18. 18. Cache Expirationcache_set($cid, $data, $bin = cache, $expire = CACHE_PERMANENT) • CACHE_PERMANENT • CACHE_TEMPORARY • A Unix timestamp 18
  19. 19. Usage Example<?php  $value = cache_get(cache_key);  if (FALSE == $value) {    // generate $value    cache_set(cache_key, $value);  }?> 19
  20. 20. Create Your Own Cache<?php  /* @file my_module.install */  function my_module_schema() {    $schema[cache_my_cache] = drupal_get_schema_unprocessed(system, cache);    $schema[cache_my_cache][description] = A cache table for my module.;    return $schema;  }?><?php  /* @file my_module.module */  function my_module_flush_caches() {    return array(cache_my_cache);  }?> 20
  21. 21. Storing objects in the database “146/365 square peg into a round hole” by rosipaw. http://www.flickr.com/photos/rosipaw/ 4643095630/21
  22. 22. Saving Objects• drupal_write_record()• Single statements INSERT/UPDATE• Use with new $fetchStyle in D7 or db_fetch_object in D6 22
  23. 23. Schema Example<?php  // use the following table schema  $schema[my_table] = array(    description => My table.,    fields => array(      id => array(type => serial, unsigned => TRUE, not null => TRUE,),      value => array(type => varchar, length => 255, not null => TRUE, default => ,),    ),    primary key => array(id),  );?>
  24. 24. Example<?php  $my_data = new stdClass();  $my_data->id = 1;    // remove this to see INSERT behavior  $my_data->value = some value;  if ($my_data->id) {    // if this is a new entry, specify tables primary key    drupal_write_record(my_table, $my_data, array(id));  }  else {    drupal_write_record(my_table, $my_data);  }?>
  25. 25. Serializing Objects• Automatically done in Schema API • Set ‘serialize’ property in field• Uses PHP serialize() and unserialize()• Best used for additional options• Simplifies database schema 25
  26. 26. Advanced Schema Example<?php  // use the following table schema  $schema[my_table] = array(    description => My table.,    fields => array(      id => array(type => serial, unsigned => TRUE, not null => TRUE,),      value => array(type => varchar, length => 255, not null => TRUE, default => ,),      options => array(type => text, serialize => TRUE, default => ,),    ),    primary key => array(id),  );?>
  27. 27. Example<?php  $my_data = new stdClass();  $my_data->id = 1;    // remove this to see INSERT behavior  $my_data->value = some value;  $my_data->options = array(    opt1 => value1,    opt2 => value2,  );  if ($my_data->id) {    // if this is a new entry, specify tables primary key    drupal_write_record(my_table, $my_data, array(id));  }  else {    drupal_write_record(my_table, $my_data);  }?>
  28. 28. Making the most of menus “271/365 Run Rabbit, Run Rabbit...” by sosij. http://www.flickr.com/photos/sharonkcooper/ 4693026005/28
  29. 29. Arguments• Title• Page• Access• Load 29
  30. 30. Title Arguments• Use with t() or custom callback• Dynamic titles from URL 30
  31. 31. Page Arguments 31
  32. 32. Access Arguments 32
  33. 33. Load Arguments 33
  34. 34. Queueing/BatchingLocking mechanisms Registry alters More tricks... Renderable arrays Theme fallbacks and suggestions
  35. 35. Further reading and code snippets athttp://erikwebb.net/blog/drupal-design- patterns
  36. 36. Questions? @erikwebbwww.erikwebb.net

×