HOWTO: Best Practices for Embedding Views in Code

Profile picture

It is a good Drupal development best practice to embed each of your views in code instead of storing them in the database. This technique will allow your views code to be managed by your version control system which makes pushing up changes to views from development to staging to live a much cleaner process. Additionally, since the views code is being loaded from disk instead of the the more expensive database you will see a modest performance improvement. All in all a pretty good thing.

However, getting this to work in practice can be a little tricky. The embedded views are *sizable* data objects and the standard implementation of the Views 2 hook to do this (hook_views_default_views()) leads to the creation of a *giant* function where each of your views is copied and pasted into your module file. Making changes to individual views later can be a real hassle.

To help solve this issue I took a cue from views implementation of organic groups and adapted a technique to allow each view to be stored in its own separate include file which is automatically detected by the module. The win here is to allow easy updating of each view (just delete its file and copy the new export over it) and not have to worry about a lot of other cruft. To make this happen, four steps:

First, you need to specify the define important hook_views_api in your module like so. This will tell Views 2 you are looking to do even bigger and better things.

/**
* Implementation of hook_views_api().
**/
function my_great_module_views_api() {
  return array(
    'api' => 2,
  );
}

Second, you need to create a file in your module directory that will include your hook_views_default_views() function. Including this as a separate file (instead of in the main module) will let Drupal decide when to pull in this hook and its pile of related views code.

touch my_great_module.views_default.inc

Third, you need to define the actual hook in the file. The code below will define that hook and will setup logic to recursively look through a "views" subdirectory for views to include as defaults. The logic below will load any file in the "views" directory and expects the files to individually contain a $view object.

/**
* Implementation of hook_views_default_views().
**/
function my_great_module_views_default_views() {
  $files = file_scan_directory(drupal_get_path('module', 'my_great_module'). '/views', '.view');
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }
  return $views;
}

And finally, forth, you need to create the important "views" sub-directory and make the many different files inside that each include a single $view object. As a development practice I name each file with the same name as the view and use the .view file extension (example: my_view.view). It is a pretty easy process to export each $view from the views interface and include in the code.

Comments

Thank you for this post. I was already planning to use Views in code for some time, but didn't take time to study how to do it.

or use the features module and let it do the hard work?

Absolutely, with a features/drush combo you can update views in code in the term with drush features update featurename

I like to have my views include files contain <?php so that text editors properly syntax highlight the view. So, I use a slightly different method to include views:

<?php
$d
= dir($path);
while (
FALSE !== ($filename = $d->read())) {
  if (
substr($filename, -4) == '.inc') {
    include
"$path/$filename";
   
$views[$view->name] = $view;
  }
}
$d->close();
?>

Enjoy!
--Andrew

PS - it would be nice if you enabled the "Name" field on anonymous comments.

I had all my views in individual files in D5 and was dismayed to find D6 wanted them all smooshed together. Then I stumbled on OG's code and snatched it up. Advanced Forum and Advanced Profile Kit both make use of it. :)

Michelle

Mbt zapatosEnciendo el televisor escuchando el diálogo de los demásMbt zapatosTal vez los que me pueden dar cuenta de la historia
Usted tiene que amar no puedo aprenderMbt zapatosImpotente viendo que la situación empeore.Sentirse realmente en serio vistazo a la situación.Yo no puedo darte el futuro ustedMbt zapatosTranquilo final del tratamiento es otro.Cuando las lágrimas para permanecer.Shangyiqiaozai
La separación es otra de Mbt zapatosentender

Add comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <br/> <br /> <p> <img> <blockquote> <i> <b> <u>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.

Client Testimonial

Chapter Three did phenomenal work for us. We were under a tight deadline to design and develop a new site for the foundation, with particular emphasis on a content management system that enabled us to define and categorize the variety of work we do with the National Institutes of Health and its 27 institutes and centers. Chapter Three worked seamlessly with our designer Flax Media to build a site that matched our content management needs. They were responsive and available for additional requests we had. I highly recommend working with Chapter Three! We couldn't be happier with the results.

Kathleen Barrett, Manager, Communications & Web Strategy, the Foundation for the National Institutes of Health

Drupalcon SF 2010