Version Control – A Visual Guide

June 14th, 2010

If you are new to version control, this article is a fantastic outline:
http://betterexplained.com/articles/a-visual-guide-to-version-control/

Lessons Learned From framework – A Dissection

June 4th, 2010

For the last two and a half years or so, I have spent time off and on working on a framework for my websites. There were a lot of reasons that I was doing this, but the main two were I didn’t like the frameworks that were out at the time, and I wanted to learn some cool new code.

So, here we are, a long time later, and I’ve decided to start from near scratch on a new version. Before I embark on that challenge though, I’m dissecting what I have learned through the process, so hopefully someone can learn at least one thing.

1. URL Rewriting
How you write URL’s is the subject of so many articles on the internet about SEO and other things that I won’t really get into it. Needless to say, it’s important to have useful and clear URL’s.

Processing those URL’s
This is one of the cool tricks I started working with. mod_rewrite rules are really cryptic (regex is cryptic), so I made it simple. Assuming you are using Apache, use this rule in your .htaccess, then never have to screw around with it again.

RewriteEngine On
RewriteRule !\.(js|ico|gif|jpg|png|css|pdf|swf)$ @yourawesomescript.php

This points all visited URL’s to your main script. Once there, dissect the URL with the following code, and process however you want.

$route = $_SERVER['REQUEST_URI'];
$base_script = CONFIG_BASE_SCRIPT_NAME; // This should be your base script URL aka /framework/@yourawesomescript.php

for($x = 0, $c = strlen($base_script); $x < $c; $x++){
    if(strtolower(substr($base_script, 0, 1)) == strtolower(substr($route, 0, 1))){
        $route = substr($route, 1);
        $base_script = substr($base_script, 1);
    }else{
        break;
    }
}

$route = explode('/', $route);
$appControl = (isset($route[0]) && !empty($route[0])) ? array_shift($route) : 'index';
$appAction = (isset($route[0]) && !empty($route[0])) ? array_shift($route) : '';
$appVars = (!empty($route)) ? $route : array();

2. Zend Framework Is Awesome!
Zend has started a project that saves so much time. The ZF is not just a framework though. Because the components are loosely coupled, you can pick and choose what you want to use as part of your project, and toss the rest. This is a huge time saver simply because it is code that you do not have to maintain.

Here’s a sample database query. Nice and clean, and Zend_DB handles both building the query (including escaping the data) and running it.

$userconf = $db->fetchAll(
    $db->select()
        ->from($config->dbschema->table_users, array('uid'))
        ->where('email = ?', $in['email'])
        ->where('actkey = ?', $in['cid'])
);

3. minify Is Also Awesome
If you are not using minify, you should be.

It combines multiple CSS or Javascript files, removes unnecessary whitespace and comments, and serves them with gzip encoding and optimal client-side cache headers.

The best reason for using minify is that you can take the 5 or 6 Javascript files you might be serving, and group them into one nice little package. You will never have to upload pre-compressed scripts to your server, and you can still serve them all compressed (gzip and packed) and optimized with one URL (1 HTTP request instead of several):

<script type="text/javascript" src="min/g=js&1"></script>

And, to save you more time, here is a sample groupsConfig.php file (reference file system layout at the bottom of this article):

<?php

$mingc_base_url = '/framework';
$mingc_base_layout = $mingc_base_url . 'layout/';

return array(
    'js' => array(
        $mingc_base_layout . 'js/jquery.lightbox.js',
        $mingc_base_layout . 'js/DD_roundies.js',
        $mingc_base_layout . 'js/base.js',
    ),
    'css' => array(
        $mingc_base_layout . 'css/main.css',
        $mingc_base_layout . 'css/jquery.lightbox.css',
    ),
);

4. Output Buffering For Amazing Awesomeness
Output buffering will save you a lot of hassle. You can pass headers at any point in your script simply by turning this on. This means that you can do things like redirecting users to another page without having to show them any content (which saves you a little hassle as a dev, and them a little time). And speaking of redirecting, that leads me into:

5. Shortcircuit The Problem (redirect_hard)
Not every page you load needs to show content. Some just need to process what you post from a form, or check if someone is logged in, or just bounce you somewhere else in a site. For these times, I have a function that I use that sends a Location: header directly to the browser, telling it to go away to somewhere else.

function redirect_hard($url = null, $internal = 1){
    if($internal){
        // CONFIG_HREF_SITE is defined as http://www.site.com/framework/
        header('Location: ' . CONFIG_HREF_SITE . $url);
    }else{
        header('Location: ' . $url);
    }
}

6. Exceptions Are Better Errors
I have seem (and written) a lot of code that handles errors in a strange way.

$err = 0;

if($x != 4){$err = 1;}
if($y != 2){$err = 1;}

if($err){echo 'Error'; break;}else{echo 'Happy ' . ($x + $y);}

There is a better, and way more awesome way to do this. Exceptions are much easier and cleaner to work with, because you can just wrap a big piece of dependent code with one big exception handler, and go to town on whatever you want to do. Here is the same functionality as above, with exceptions:

try{
    if($x != 4){throw new Exception('x is not set!');}
    if($y != 2){throw new Exception('y is not set!');}
    // If either condition is not met, and an exception is thrown
    // then the code below here is not executed.
    echo 'Happy ' . ($x + $y); 
}catch(Exception $e){
    echo 'Error: ',  $e->getMessage(), "\n";
}

Now, of course, it looks a little more complicated in this small example, but imagine if you had a half-dozen events that you were executing that could throw an error. With exceptions, your execution of that particular try{}catch{} block would stop as soon as one of these events occurred, and you would know precisely where. Learn and love exceptions and exception handling, because it will save you a lot of mess.

7. Components Are So Generic
You have a form that you use for both adding and editing a food, for example. Well, you could build the form once, then copy-paste it into the two places where you will use it. Of course, then you need to make sure that when you make changes, they stay in sync. Easy enough if you only have a form in two places. Imagine though, that you have a form that you use in a half-dozen places.

Make it into a component, because less code is always easier to maintain. Below is a wrapper component that I use around every form I create. All I have to do is make sure that I set the form URL and content, then include this piece of code. It doesn’t seem like much, but now, I have removed 6 lines of HTML from every form I create, and I have a centralized control over the form.

$page_content .= '
<div class="center_div">
  <form action="' . $form['url'] . '" method="post">
    <div>
' . $form['content'] . '
    </div>
  </form>
</div>
';

If you have a piece of complex code in more than two places, do this instead.

8. Have A Config File
This is a simple lesson. Never put any variable that relates to any configuration anywhere but in this file. Database settings, the constant for PI, the name of your website, they all go here. Everything is so much easier when the only change between your production and development environment is your config file.

9. Hold The Mail
I have seen a lot of approaches to mail. Some say fork it, some say send it and make the user wait. I have a more interesting solution. I built a mailqueue script. What happens when I want to send email is it gets placed in a database. There is a script attached to a cron job (a task on a timer), and it is called every 5 minutes. The only thing this script does is check the database and send the email sitting in the queue. The benefits of this are:

  1. I don’t have to make a user wait (hitting a database will likely always be faster than sending an email on a high load server)
  2. Email sent can now be logged
  3. All sending on the backend can be taken care of in a speedier language (perl or c)
  4. I have precise control over how much mail is processed in a day, so I can throttle it as needed

Classes Are Classier
Again, another topic that has been written about extensively. Here is the shortlist of why I find classes awesome.

  • Everything is accessible through one discreet interface ie $db->connect, $db->select()
  • Once it’s written, it’s easy to maintain and expand, and still all through that one interface
  • You can move it so much easier
  • No mucking around with variables that you need to keep track of ($age, $height, $weight can all be inside $person, so you can $person->get(‘age’))

I hope that all this information is useful to someone else, and if you have any comments, feel free to let them be heard.

Reference Filesystem Layout

http://site.com/framework/
/framework/
/framework/.htaccess
/framework/@yourawesomescript.php <--- Base script /framework/min/ <--- minify directory /framework/layout/ /framework/layout/js/ /framework/layout/css/

WordPress - Entries (RSS) and Comments (RSS) - © 2011 Ben Dauphinee