Thursday, May 22, 2008

Absolute Paths and Relative Paths

Lately, I've had to grand experience of fighting my own terrible code. I've been doing PHP work for about 18 months now, and my early work was pretty bad. In the past year, I've made great strides in improving my code, but I still have a lot of old work that is still in place. This week, one of my main projects is setting up a local development environment so I can freely work on sites without fear of disabling an active website.

One problem I keep encountering was my old tendency to declare absolute paths. I would define all includes and links by giving the exact file location, rewritten each time. Nowadays, I would never be caught doing something so foolish as rewriting the same file path over and over. Now, I would define a constant at the very beginning of an MVC website, and for the rest of the time the script is executing, in pulls files in relation to that constant.

By setting things up in this manner, I'm using the best of both worlds. I have the security of using an absolute path that can never be confused on a file's location, and the flexibility of a relative path that can be relocated and still functional.

The best way that I've yet found is through a series of constant definitions at the start of every site:


define('ROOT_DIR', dirname($_SERVER['SCRIPT_FILENAME']) . "/");

define('HTML_ROOT', "http://" . $_SERVER['HTTP_HOST'] . "/" . str_replace($_SERVER['DOCUMENT_ROOT'], '', ROOT_DIR));



The first definition defines the root directory that the site will be executed from. By placing the index.php file in the main directory and then using the dirname() function, you can locate the full path for the main directory. Unlike using the $_SERVER['DOCUMENT_ROOT'] variable, this can account for a site that isn't at the root level of a site.

The second definition defines what should precede all URLs listed within the site. By putting that constant infront of all CSS declarations, Javascript declarations, images, and links, you can be assured that the file will always be properly found.

For instance, if your main domain is http://my.domain.com/user/directory/site/, the CSS link of /styles.css will go outside the site folder and go back to the root folder. However, adding this constant before the call will change it to http://my.domain.com/user/directory/site/styles.css, without you worrying about it.

As you can see (and see even better if you try it), by declaring the absolute path constants at the start of the site, and basing those declarations on a series of function calls that analyze the current page, you can make use of both absolute and relative paths. The constants are defined on a fluid, yet reliable, method, and those constants are absolute and safe. A site built with this in mind can be moved to any domain at any time and every line of code will still work flawlessly.

No comments: