You are hereBlogs / Jeff Schuler's blog / Building APIs that Rock (DrupalCon 2009 notes)

Building APIs that Rock (DrupalCon 2009 notes)


Posted by Jeff Schuler - on 04 March 2009

Building APIs that Rock

Jeff Eaton
9:00 AM, 2009-03-04

Official session notes

 

Why APIs?

  1. let other code use your features
    • Focusing on writing modules that provide a nice interface to code as well as humans
    • Examples of modules with nice APIs: Views, OG, Flag
  2. hide complexity
    • Better to write modules that use underlying functions than "pretending" to be a user and using forms
    • hides whether ImageMagick or GD tools (or other lib) is being used
    • provides "rotate" "scale" "crop" Messaging
    • abstracts /how/ messages are being sent
    • cache_get, cache_set (inside Drupal)
    • provide simple interface to hide method underneath (memcache, etc)
  3. Agreement about how things get done

Example: Creating VotingAPI

  • started by tearing apart someone else's module
  • find nouns: votes
  • find verbs: get / set

Example: myapi_do_something()

  • don't use enums and hard-coded numbers unless you know it's something that won't change
    • use strings to allow others to make their own new type
  • well placed hooks allow other people to do the hard work for you!
  • module_invoke_all()
  • drupal_alter(): "it's like passing around the doobie of data" : everybody gets a chance. (you don't have to...)"
  • hook_form_alter()
  • hook_menu_alter()
  • who wants to hijack this before it hits the page?
  • let other modules have a chance to change or add more data
  • "template" design pattern
  • "if you build it they will hook"
  • layer verbs to hide complexity
  • account for new users

7 deadly sins

  1. Lone Ranger (reinvents wheel, ignores conventions, ignores related apis... common to newcomers
  2. invisible Assumptions (assuming the global $user, checking arg(0), assuming logged-in users... common to UI-centric modules
  3. Helping them to Death ("while i'm at it, I'll set the breadcrumb, send an email, and add links, and... common to bloated modules
  4. Leaky Abstraction ("just use this function... and learn everything that's underneath it! ... common in complex problem domains. Simplify! Assume sensible defaults, and get out of the way when appropriate
  5. Fake Flexibility (Providing hooks that don't really provide the functionality they portray
  6. Mission Creep (even worse than feature creep .. common with "solve a big problem APIs. Split it into smaller APIs!
  7. Dependency Soup (Flip-side of Mission Creep. Focus focus focus! Make dependencies optional, pray for a package manager in Drupal

Rules of Thumb

  • cooperate
  • don't assume too much
  • do't be pushy
  • simplify or step aside
  • test your extensions
  • stay focused