Latest blog post: 10 Epic Dribblers That You Should Be Following →

Archive for the ‘Programming and Methodology’ Category

Organizing, managing and deploying PHP projects in subversion (SVN)

Managing projects in SVN can be difficult, especially if you are just starting out. Hopefully I can clear out some common misconceptions about source control and help you understand it a little better.

Many prefer to use command line but I find a GUI tool like Cornerstone, Versions or Tortoise to be easier for beginners to work with. For this tutorial I will be referencing Cornerstone 2. Also, this guide is meant for those who are already slightly familiar with the basic concepts of SVN. It does not go into detail about setting up SVN, though I will recommend beginners to checkout Beanstalk – a web based tool for setting up and managing SVN/Git.

How does SVN work?

All you really need to know is that SVN provides a way to store all of the revisions made on your code-base to a remote (or local!) repository. Each time you commit your code to this server it will create a revision number associated with that set of code. This allows you to compare different revisions of your code and to branch off into new lines of development without getting different versions mixed up.

SVN also makes it easy to work in a collaborative environment. Multiple coders can work on the same code-base and their changes will be merged together by SVN and given a revision number. Here are some important terms to understand about SVN:

Repository – The repository is the main folder that stores your SVN files. It is typically organized into 3 folders. Trunk, Branches and Tags.

Trunk – Think of your svn repository as a tree. The trunk is where the main code-base is found. While not all SVN setups are the same, the trunk will generally contain the freshest development copy of your code.

Branches – SVN, like a tree, can be branched. A branch is generally a line of development that contains a copy of the main code-base from the trunk but is worked on separately. Branches are great for fixing bugs, testing new functionality and adding new features without disturbing the main code-base found in your trunk.

Tags – A tag is basically a snapshot of the code at a particular revision. Let’s say you just released version 1.0 of your code and you want to make sure you have a separate copy of the code that will never change, you would make a tag of it. This way you always have a copy of the code that you deployed or checked out in case you need to revert back to it or examine it for whatever reason. A tag is typically made of either the trunk or a branch.

Checkout – Checking out code from a repository gives you a fresh copy of the latest revision of the code-base. At that point the directory on your system that you checked out the code to basically becomes a mirror of the repository. You can then start editing the code and committing changes!

Commit – Once you have checked out your code, worked on whatever it was you wanted to get done and have completed it, you would then commit the new code to the repository. Each commit adds a new revision number to the repository so you can always see what the code was like before that commit.

Update – Let’s say the last time you checked out the code was yesterday. If you are working with a team of developers then one of them may have committed a change since the last time you updated or checked out the code. Updating will bring your code to the latest version of the code. You would also typically update before a commit. This way if there is a conflict that must be resolved, you can fix it locally instead of remotely.

Conflict – A conflict occurs when SVN can’t figure out how to merge two different changes. This means you will have to manually decide what to do about that particular conflicted code. Cornerstone (and other GUIs) will show you the conflict in the code and ask what you want to do with it, typically using a function called diff.

Merge – Let’s say you made a branch off of the trunk in order to add a new feature. Once that feature is complete you would merge it back into the trunk so that it could be part of the main code base. You might also follow this same method for bug fixes.

How do I manage releases, bugs and changes in SVN?

I mentioned this briefly in my explanation of the terms above but it is important enough to go into more detail about. Before even writing your code, it can be a good idea to develop a basic build and deployment strategy to keep your code versions organized.

Here is a graphic of a recent build strategy that I used. I’ll go into detail about what all these lines mean:

Dev & Release Cycle

In this diagram the trunk is represented by a straight line of development. This is the main code-base which is checked out and worked on for implementation of new versions and features. Since I am the sole developer on this project it is alright to use the trunk as my main line of development. However, in a multi-dev situation you would likely branch off and each dev would merge changes and fixes from their branch into the trunk. There really isn’t a set methodology for this and it’s best to simply find out what works best for your project.

In the diagram above you will see a branch off of the trunk called RELEASE-v_v. This means that when version 1.0 of the software is released, we branch out and call it RELEASE-1_0. Once we create this branch, all changes/updates/fixes that need to be done to the live site occur in this new branch and not the trunk. The trunk is instead used for the new version and features of the site. However, you will notice that if a bug fix is made on the RELEASE-1_0 branch it is merged back into the trunk. This will keep the core code in the trunk up to date with the live site throughout development.

There was also a TAG created when we made the branch for RELEASE-1_0. This is good practice because it gives you a snapshot of what the software was like at key moments in the development process. In this case it’s a snapshot of the initial release just before it was deployed.

You will also notice the I am branching off for major bug fixes to the main code base. This is good practice because, when you run into a major bug, you may need the option to revert back to the code PRE bux fix or POST bug fix. Branching off and creating snapshots of both PRE and POST are a great way to revert back if necessary or to just view the code at a later date. Once the bug is fixed, that branch is merged back into the trunk and the bug branch is deleted (remember we still have our PRE and POST tags though).

Deployment

Many beginner’s have a hard time understanding the concept of deployment to a web server. This is because they have typically used FTP to update their production copy of a particular code-base. This can be confusing and cause a lot of problems. The solution is deployment. There are many choices when it comes to deployment software (Hudson, Capistrano, Phing) but I typically use Beanstalk. They offer a simple interface and setup for web deployments. All you have to do is input your ftp credentials and manage some settings and they do the hard work for you!

I usually have a branch in my repository that I deploy from to specific environments (top right of the deployment graphic). Basically, when the code is ready I just merge the new changes into the branch I would like to deploy from (qa, stage and prod usually) and that is where my deployment is set to run.

Here’s the typical deployment process that I use:

  1. Initiate deployment (usually by clicking a Build or Deploy button within the deployment tool)
  2. Mkdir www/new.example.com on your web server
  3. Upload latest codebase to www/new.example.com (This is handled automatically via FTP by Beanstalk)
  4. Rename config files (in my case I run mv config/core.prod.php to config/core.php and config/database.prod.php to config/database.php).
  5. Copy www/example.com to backups/example.com.bk (Creates a backup of the current version of the website. This is great if there is a problem because all we have to do is make this backup live and we are back where we started!)
  6. Mv www/new.example.com to www/example.com. This will make the latest uploaded copy of the site go live immediately.

Notes on deployment

Deployment software will typically allow you to run a script before the deployment and after the deployment. In Beanstalk’s case they are called hooks. These files are where you run the above commands to get your deployment all set up. Once you have your hooks ready to go and tested then all you have to do is click “Deploy” and viola! Your latest code is live!

Also, you typically want to keep your config files (like core.php and database.php in my case since I typically use CakePHP) out of your repository. Instead you should keep a copy of each called core.dev.php and database.dev.php. When the code is checked out, the dev can rename the appropriate files so that they can customize these files for their setup. We use a similar process for deployment to qa, staging or production, respectively.

Conclusion

Well I hope this clears up some of the confusion surrounding SVN. If you have any questions or criticisms feel free to leave me a comment or ask me on twitter. Thanks for reading!

The Future of the Cloud

The cloud represents a paradigm-shift in traditional computing. It’s a scalable, seemingly infinite source of resources to grow and expand your web application. The cloud also represents a shift from desktop software to web based software that is primarily accessed through your web browser.

The basic concept of cloud computing dates back to the 1960s. John McCarthy stated that “computation may someday be organized as a public utility” and most of the characteristics of cloud computing were explored in Douglas Parkhill’s book “The Challenge of the Computer Utility” in 1966…

Read the full article on ThinkVitamin.com

Drupal 6 image paths in template files

I had a hard time finding much info on this in a Google search so I figured I would post the simple answer. In order to include images in your template files you must include the path relative to your installation. Assuming your template images are in the images folder, this is done with the following code:

<img src="<?php echo $base_path . path_to_template(); ?>/images/picture.jpg" />

The Perfect Development Environment

Developers will argue all day that a particular development setup is better than the next but we can all agree that having a development environment that is both comfortable and efficient is crucial for creating great software and meeting deadlines.

Here I will be covering, in detail, my ideal development environment. Some of it you will agree with, some of it you will disagree with, but hopefully this can help you refine your own development environment and question your current setup.

Read the full article on Think Vitamin

An Overview of Smarty Templates & Other Comparisons

The template engine’s job is to help separate out application model logic from display logic and to provide a simpler, more readable way to add functionality to your display files. Since HTML was never meant to handle arbitrary logic, it is generally kept separate from the Model and Controller layers of an application..

Read the full article on OXP

Tutorial: How to create a simple drag and drop with jQuery

Let’s face it, creating drag and drop functionality with JavaScript alone is tough. What would have taken me hours with JavaScript now takes me a matter of minutes with jQuery. Drag and drop is so beneficial for a web page because it makes it seem more like a desktop application and we all know that that’s where the internet is headed. So here is a quick tutorial to help you get up and running with jQuery drag and drop.

Click here for a demo of what we’ll be making.

1. Create the HTML elements

To use jQuery drag and drop in it’s basic form, there really isn’t any special markup required. Here is the basic setup that we’ll be using:

        <div id="trash" class="out">
                <span>Trash</span>
        </div>
        <div id="items">
                <div class="item"><span>Item 1</span></div>
                <div class="item"><span>Item 2</span></div>
                <div class="item"><span>Item 3</span></div>
        </div>

And here is some some quick css to get the page looking right.

body {
        font: bold 12px arial;
}
 
span {
        float: left;
        margin-top: 17px;
        text-align: center;
        width: 100%;
}
 
#trash, #items, .item {
        height: 50px;
        width: 50px;
}
 
#trash {
        color: #354e62;
}
 
#items {
       margin-top: 10px;
       width: 100%;
}
 
.item {
        background: #cdcdcd;
        color: #3b3b3b;
        float: left;
        margin-right: 10px;
}
 
.over {
    background-color: #cedae3;
}
 
.out {
    background-color: #a6bcce;
}

So here we are setting up a simple example of a drag and drop scenario. We have a bunch of items and a trash bin. We want to be able to drag those items and drop them on the trash bin and trigger a function. Now let’s get ready to code some jQuery!

2. Download and include jQuery files

Drag and drop functions require both the jQuery library and jQuery UI. The jQuery UI website allows you to only download the parts you need so click on “Build custom download” and be sure to include all the UI Core elements plus Draggable and Droppable interactions. Download your custom jQuery UI file and include both the jQuery 1.4 library and the jQuery UI tools in your head of your document like so:

<head>
      <script type="text/javascript" src="js/jquery1.4.2.js"></script>
      <script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>
      <!-- We'll be writing our jQuery in dragdrop.js -->
      <script type="text/javascript" src="js/dragdrop.js"></script>
</head>

3. Create the draggable elements

So let’s get started coding some jQuery. The first thing we need to do is make the items on the page draggable. This only involves a few lines of code:

$(function() {
        $(".item").draggable();
});

That’s it! Reload the page and checkout your new draggable elements. You’ll probably notice an immediate issue. The draggable elements don’t snap back into place. Instead they simply stay wherever they are dragged to. This can be fixed by enabling the ‘revert’ option:

$(function() {
        $(".item").draggable({
                revert: true
        });
});

That’s a lot better. Now we have some nice draggable elements on our page that snap back into place.

4. Create the droppable element

Now that we have our draggable elements, we need a place to drop them. That’s where jQuery Droppable function comes in. All we have to do is declare the trash div as droppable much like we declared the page items as draggable earlier.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable();
});

Now this alone won’t do much. Let’s go ahead and add an alert when an item is held over the trash can so we know that it’s working.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                over: function() {
                        alert('working!');
                }
        });
});

When you hold your cursor over the trash box while you are dragging an item, you should see ‘working!’ in a javascript popup. We are nearly in business. Let’s improve on the overall functionality just a bit. By using droppable’s ‘over’ and ‘out’ options we can make the Trash can change colors when an item is hovering over it.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                over: function() {
                       $(this).removeClass('out').addClass('over');
                },
                out: function() {
                        $(this).removeClass('over').addClass('out');
                }
        });
});

5. Create a deletion confirmation event

Since we are sending these items to the trash. Let’s make a quick alert that asks the user if they would like to proceed. This can be done by adding a function on to the ‘drop’ option of jQuery’s Droppable function. We also need to remember to change the background color of the trash box back to normal since ‘drop’ skips over the ‘out’ function.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                over: function() {
                       $(this).css('backgroundColor', '#cedae3');
                },
                out: function() {
                        $(this).css('backgroundColor', '#a6bcce');
                },
                drop: function() {
                        var answer = confirm('Permantly delete this item?');
                        $(this).removeClass('over').addClass('out');
                }
        });
});

6. Altering the highlight area

You may notice at this point that the droppable item is only triggered when your cursor actually moves over the droppable element. This may be the functionality you want but I prefer for the box to trigger the ‘over’ event when the actual item intersects with the trash box. This can be changed easily by setting the ‘tolerance’ option in our droppable function.

$(function() {
        $(".item").draggable({
                revert: true
        });
        $("#trash").droppable({
                tolerance: 'touch',
                over: function() {
                       $(this).removeClass('out').addClass('over');
                },
                out: function() {
                        $(this).removeClass('over').addClass('out');
                },
                drop: function() {
                        var answer = confirm('Permantly delete this item?');
                        $(this).removeClass('over').addClass('out');
                }
        });
});

Conclusion

Using the jQuery library with jQuery UI tools we were able to quickly replicate the drag and drop functionality that is commonly found in a desktop application. While this is a basic example of how you can utilize jQuery’s drag and drop functionality, this can be easily expanded by triggering a jQuery.post function on drop that actually removes the item from the database. Then you could reload the results in the items div, creating a working drag and drop file/item manager. The possibilities for this really are endless.

You can download the full source of the tutorial and checkout a demo here.

Well I hope you enjoyed the tutorial and hope it helps you get started using jQuery drag and drop. Did this help you out? Would you do anything different? Please let me know in the comments section below!

My First Impressions of CakePHP

So I recently decided to look into some of the different PHP frameworks and pick the one I thought might be the best. I looked into CodeIgniter, Symfony and CakePHP but ultimately chose CakePHP. My decision came after researching and watching videos found on each framework’s website and checking out various speed tests. CakePHP seemed to be the most attractive to me. It has excellent documentation, a great website, and a fairly active community, plus I just liked the way it was organized and implemented more so than CodeIgniter or Symfony. CakePHP was the the slowest in speed tests though, but it wasn’t a large enough difference to worry me.

Initial Thoughts

My initial thought of CakePHP after getting it setup and looking over some of the documentation was “Wow this seems complicated”. There is a certain methodology behind CakePHP that should usually be followed closely, but there’s definitely a learning curve which made it kind of frustrating at times. I found myself searching Google often for anything that wasn’t covered specifically in the Cake Book. It seemed though that with every problem I solved, I learned a little bit more about Cake best/common practices which helped me become more familiar with the framework.

After working with it for a week or two

Once I got the hang of organization, validation, form automagic and Auth for user authentication, I was starting to fly through some of the things that initially took me an hour to implement. I really think it just comes down to being determined and not getting discouraged when it seems like you’ll never get the hang of it.

Conclusion

Overall I am very impressed with CakePHP and am kinda sad that I waited so long to start using it. The way it handles form validation is so simple and intuitive, all the auto-magic that happens behind the scenes is un-obtrusive yet very customizable and your code remains Object-Oriented and organized very logically. While I still don’t know much about CakePHP, I am confident that which each problem I solve, I will become that much more familiar with the framework and begin decreasing development time dramatically while maintaining a more organized code base. So, if you haven’t tried CakePHP, I suggest you do and tell me what you think!

PHP Project planning for idiots – MVC design pattern

Proper planning is arguably the most important aspect of any project. Without a plan projects will exceed deadlines, coders will create redundant code and many projects won’t even see the light of day. So my goal with this is to help the beginners out there so they don’t have to go through what I did as a novice PHP programmer. Hopefully this will get you on the right track with proper project planning and creating your app using the Model View Control (MVC) design pattern.

Requirements: This tutorial assumes that you are familiar with OOP in PHP as well as Classes and have some basic knowledge of databases.

What is MVC?

MVC stands for Model View Control. It is an architectural pattern that attempts to keep your code more organized and running more smoothly and helps others to pick up where you left off later.

Model

The model is the logic of your program. This is where all of the actual thinking and calculating happens. Let’s say you have a blog that users can post comments on. The actual function that analyzes the new comment data and writes it to the database is in the model.

View

The view is what the user or visitor sees. It is the template that holds the actual design markup that displays and formats the page or section the user is currently viewing. Using the blog example, the view would be the actual html files that make up your blog’s overall design.

Controller

The controller is what determines what needs to be run in the model or what view needs to be displayed. The decision of what is displayed or run is generally determined by some kind of user input or action. It is basically the backbone of your app. Back to the blog example, say the user visits a blog post at mysite.com/blog/?post=12. The controller sees this input and tells the model to grab post id 12 and then sends the data to the view which in turn formats the data so the user can see the page.

Planning your project

Creating a web app in PHP can be a pretty daunting task. Here are the steps I take when planning out my app.

Brainstorm

The best thing to do is to open up a new Google Doc and start jotting down ideas. Try to keep it somewhat organized as this will come in handy later on. I also like to put an objective at the top of the doc just so I have a clear idea what my goals are, usually just a few sentences.

Designing your app

I am a programmer and a designer so I usually have a hand in the design process. Just in case you are like me, here is my advice. Make sure you have a clear idea of what the software is going to look like. This might include designing out the entire thing in Photoshop down to the last detail before you even write a line of code.

If you think a simple wireframe of the design will suffice, checkout a program like Balsamiq. This is an awesome program that lets you easily create a wire-frame of your entire site. As far as sketching software goes, this is the best I’ve found. Did I mention it is easy!?

Balsamiq

A layout created using Balsamiq

Plan out your major functions

Before you begin writing the actual code, it’s a good idea to create a visual representation. This can dramatically cut down on development time and bugs. UML (Unified Modeling Language) is a great tool for creating a wire-frame of your functions. You can checkout a list of programs that use UML for creating function diagrams here. Or you might prefer using mind-mapping software, in which case FreeMind is absolutely awesome!

Using the blog example, at the very least I would create a diagram of the posts class, comments class and user management/login.

Create the Framework

First, think about your directory structure and write it out in a way that is organized and makes the most sense to you. Think about where your controller will reside, where your template files will be stored and where your model files will be stored. It may be beneficial at this point to look into a template engine such as Smarty. Template engines aren’t for everyone but I prefer using them over writing PHP directly into my templates.

Once you have your framework all planned out, implement it one step at a time. Start with some empty views and model skeletons and some test cases in your controller.

Mapping out the database

Although I could write an entire article on database architecture and planning (which I might actually do!), i’ll just try and give you some key points to keep in mind. First off, outline your database tables and relationships with a program like FreeMind or even plain old notepad. Research MySQL Data Types and decide which type is appropriate for each field before you actually create your database. Also, keep your database relational. It’s important not to try to stuff everything in as few tables as possible and it helps to keep your database organized. If you feel like you are missing some things, just do the best you can and move on. Some things will inevitably be thought of and added later on.

Prioritize and take it one step at a time

Once you have the basic framework and skeleton of your app and the database created, decide which section of the app to tackle first. I was once told that a good method is to visualize that you are the user and begin coding in the order of how the user might use your app. Back to the blog example, tackle posts first. Create the posts class and grab the post from the database based on the postid in the URL and output it to the page. From posts move on to the comments system and then finally to user management.

Your app will likely be much more complicated than the basic blog program I have mentioned, but hopefully this can get get you started in the right direction. Feel free to leave any questions or improvements in the comments section. Thanks for reading!

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

The best way to contact me is through one of the networks on the left or by emailing me at
ericbieller [at] gmail [dot] com.