16
08
2007
Drupal Tip: writing ‘relocatable’ code
Posted by: miquel in Drupal, PHP, Programming and ScriptingA problem which often arises when writing Drupal themes, modules, etc. is making sure there are no ‘hard-coded’ paths in our code. To help new users on their quest to writing quality Drupal code I list here the most used API functions to get paths in a portable way:
- global $base_url - A global variable which stores your sites URL, typically http://www.<your_site>.com. This variable is set in your settings.php configuration file. This is not very portable and maybe in the future Drupal has a function for this.
- base_path() - Returns the base URL path of the Drupal installation. At the very least, this will always default to /. This is used, for example when you want to add a resource relative to your base_url. For example like so: drupal_set_html_head(’<style type=”text/css” media=”all”>@import “‘. base_path() . drupal_get_path(’module’, ’system’) .’/system.css”;</style>’);
- conf_path() - Based on your sites URL tries to find the most appropiate settings.php (site configuration file). To read how it works see Drupals API documentation
- drupal_get_path($type, $name) - Returns the path to a system item (module, theme, etc.). The $type argument can be ‘theme’, ‘theme_engine’ or ‘module’ and $name the name of the item for which you want the path. To get an absolute path you need to prefix the $DOCUMENT_ROOT (the document root of your drupal installation).
- path_to_theme() - This points to your theme’s path on the local filesystem. Usually $DOCUMENT_ROOT/themes/<your_theme> or $DOCUMENT_ROOT/sites/<your_site>/themes/<your_theme>
- path_to_engine() - Returns the path to the currently selected engine.
To learn a bit more search for this terms in the API search box or ‘use the source, Luke!’.
Entries (RSS)