Clean code, and how to write it

Note: the article was originally circulated on #cleancode and #kohana on Freenode and is now recorded here as an archive. It seems very useful as something to link people to on IRC when they have questions, so feel free to share as well.

At SevenStrokes, we practice Clean Code. Although code speaks louder than words, at the moment my public repositories are heavily outdated. What isn’t as outdated, however, is a short introductory guide I wrote on Clean Code for the internal use of SevenStrokes. Although it is a guide which focuses on the basics, it does make some assumptions on the reader having some knowledge about programming. You’ll notice that the examples are primarily written in PHP, but are applicable in all languages.

Clean code architectures

The article answers the question of why good code matters, what is good code, and covers the three pillars of good code: syntax, architecture, and workflow. It shows coding examples of how to write good code, introduces you to the more abstract architectural jargon, and different tools and processes out there.

Without further ado, please click to read: SevenStrokes: Learn how to write Good Code.


Application design polish.

Free software is great. Everybody loves free stuff. However there’s one common flaw experienced by a lot of free software – they look ugly.

The reason behind this isn’t because we have too many programmers (yes, we know you never have enough programmers) and have too little artists – no, the problem is a lot more subtle. The real problem is that there is no clear hierachy within the artists. There is no control. There is no clear structure, focus, and branding. The question so many artists fail to ask ourselves as a contributor to free software is – What do we want to communicate?

To illustrate my point, I would like to use Ubuntu as an example. Regardless of your prejudices for the distribution and/or Canonical, they did do something right – they have a brand. They have a clear, recognisable pallette and style – from colourschemes to typefaces. Why don’t you see it for yourself: go and visit Notice the colours. Notice the icon styles. Notice the typography.

Another example of a project taking the steps in the right direction is KDE and their Oxygen iconset + plasma "Air" attempt. However there is still far to go.

However the issue does not lie with such large FOSS projects such as the above mentioned. Instead the real problem lies with smaller software and application created by smaller developer groups. The reason is because these small applications rarely have to worry about problems such as branding – instead they have to focus on creating an elegant application. Design elegance can only rely so far on the design of widgets in the UI toolkit used. The rest is really up to the developer. Allow me to give a quick visual example of Blogilo, a blog client which I’m using to type out this post. Take a look:

The untrained eye would not see any problem with the screenshot – however the application design above screams complexity. There is no elegance. There is no simplicity – no "flow" (a clear step by step separation of functions). A blog client is not a complex application like an IDE. It exists for you to add, edit, and delete blog posts. Nothing more. When stripped down to its basics, a blog client is naught more but a rich text editor with a few extra options. Instead we have frames within frames, accordion panels, tabs, and buttons strewn about. Overkill, in my humble opinion.

Design polish is a very hard topic to separate what is ugly and what isn’t. It’s blends over into many neighbouring topics such as usability, a macro-view of marketing (in this case, Blogilo is part of KDE), and functionality. If you are interested, however, I would like to direct you to this very interesting blog by Troy Sobotka, one of the folks behind Ubuntu, who discusses this in much more clarity and detail than I am capable of.


WIPUP 19.03.10a released!

WIPUP is a flexible and easy way for people to share, critique, and track works-in-progresses.

Every month, the WIPUP website gets synchronised with the Git repository hosting the code. It wasn’t long ago at all since the February sync was performed (21.02.10) and since I’ve been having mock exams that generally means I have a lot of free time (well, a couple all-days after the mocks) which I’ve been a busy little bee whacking down features. So while I was initially fearing a "maintenance sync" I’m happy to announce a feature-packed release.

Release notes are in their full glory in the WIPUP Release, and comments should be left there, not here.

This is a massive update, and I highly recommend people to start checking out the rest of the site and try it out themselves.

Well, time for a break from updates then!


Make a category not considered as a post in WordPress

In other words, how do you make posts that are in a certain category not count towards total page post count in WordPress?

A while back I set up Asides on this blog. The problem was that previously I was displaying 5 posts per page. Now with asides it still displayed 5 posts per page, but as asides are probably one sentence long at most I personally don’t consider them to be blog posts. This meant that it didn’t display 5 “real” posts per page. So, how do I fix this?

Disclaimer: I’m not experienced in the under-the-hood of WordPress and as a result some of this solution might be hackery. However it works for me, and that’s what counts.

Problem 1: displaying 5 real posts per page regardless of how many asides there are.

WordPress loops through a series of posts per page and displays them one by one. Initially I thought they would increment a counter, of which I could easily change so that if the post category was in “asides”, it will not increment the counter. However there were a couple flaws: 1) There was no counter, or I completely missed one, 2) The database queries sets the LIMITs from the administrator settings right at the very beginning, and 3) pagination will be completely messed up.

The solution was pretty simple, firstly we set the database query LIMIT to an obscenely large amount – more posts than we ever think we’ll need on a page. This can be done in the administrator panel. Change “display posts per page” to a random large value. I chose 15 because it seems pretty realistic that real posts + aside posts < 15 for 99.9% of the time.

The second step is to manually change the criteria for when the loop terminates. This way it will not actually show 15 posts, but instead up to 15 posts. What we’ll do is create a new counter, where ever time we display a post that isn’t an “aside”, we increment the counter, until it hits 5 posts (if I wanted 5 real posts per page) – at which time it’ll terminate the loop.

This can be done in the wp-includes/query.php page. To begin with we’ll need a new variable in the class for our counter. So below class WP_Query { we should add:

var $counting_up = 0;

Just to make sure that $counting_up resets itself as it should, we’ll add this to the init() function:

$this->counting_up = 0;

Now the next step is to modify the the_post() function. When the loop has started and the category is not an aside, we’ll increment our counter. In this example my aside category ID is category 429. This will be different for you, so you change it. So simply add this to the the_post() function:

if ( !in_category(429) && $this->current_post != -1 ) {

Now we’ve got our counter, we’ll set up the loop to terminate correctly. This can be done in the have_posts() function. Notice this is the have_posts() function inside the WP_Query class, not outside. We can modify our if statement to terminate when our counter hits 4 posts (as the first isn’t counted – therefore in effect we’ll display 5 real posts), and also when we don’t have a do_not_terminate variable set to the WP_Query. Why this do_not_terminate variable is important is if we ever need to override this, as well as later I’ll explain when we look at pagination issues. Here is my completed modified if statement:

if ($this->counting_up == 4 && !$this->query_vars['do_not_terminate']) {
$this->in_the_loop = false;
do_action_ref_array('loop_end', array(&$this));
return false;
} elseif ($this->current_post + 1 < $this->post_count) {
return true;
} elseif ($this->current_post + 1 == $this->post_count && $this->post_count > 0) {
do_action_ref_array('loop_end', array(&$this));

Now we’ve solved problem 1, and 5 real posts are displaying on our front page, let’s move on to problem 2.

Problem 2: previous page, or going to older posts will no longer work.

Since pages are pretty obsolete at this point, we’ll switch to using offsets. This is because each page will no longer display a fixed number of posts, each may display a variable amount of posts, minimum being 5 (that we set just now), and maximum being 15 (that we set at the very beginning). So to start we’ll hop over to our index.php in our theme file, and simply get the offset from the URL and pass it through to our post loop. Here goes:

<?php if ($_GET['offset'] && is_numeric($_GET['offset'])) {
query_posts('offset='. $_GET['offset']); $offsetting = $_GET['offset'];
} else { $offsetting = 0; } ?>

So with that code in index.php, we can now visit and offset our posts by 20. To determine how many posts to offset by in previous pages, we simply take how much we’re currently offset by, and add all the posts we’ve displayed on the page, regardless of whether or not it is an aside or a real post. To do this we need another counter. So we’ll initialise our counter, perhaps near the beginning of index.php:

<?php $on_page = 0; ?>

… then within our while (have_posts()) { loop, (or whatever equivalent loop your theme uses), we’ll just increment it:

<?php $on_page++; ?>

So then we recode our “previous posts” link to go to:

<a href="<?php echo $offsetting + $on_page; ?>" >Previous posts</a>

That was simple, eh? This brings us to problem 3.

Problem 3: newer posts don’t work, for obvious reasons.

Going forward in time is a little bit more complex. We want to calculate how much less we should offset by. To do this we’ll create a function to calculate this. The function will need to know how much we’re currently offset by. Based on that, it’ll query 15 posts into the future, then loop through those posts in reverse order. If it can’t go 15 posts into the future (eg: on the first page, and perhaps the second), it’ll go as far into the future as it can. When looping through, it’ll record the category of each of the posts. Whenever it hits a post, it’ll increment the count we want to offset less by. When we hit a post that category isn’t an aside (category 429 in my example), it’ll increment a counter that determines how many real posts we’ve hit so far. So therefore we have two counters. When the real counter hits 6 posts, it’ll terminate the offset counter. This is because I want 5 real posts per page, and based on how we coded problem 1, we know that the last post of any page must be a real post, not an aside.

We can place this function in the functions.php file of our theme. Here is the function, of which lazy people can copy and paste:

function back_to_the_future($offset = 0) {
$new_offset = $offset-15;
if ($new_offset < 0) {
$new_offset = 0;
$diff_offset = $offset - $new_offset;
$future_query = new WP_Query(array(
'showposts' => $diff_offset,
'order' => 'DESC',
'offset' => $new_offset,
'do_not_terminate' => TRUE

$post_data = array();

while ($future_query->have_posts()) {
if ($diff_offset == 0) {
} else {
$cat_id = get_the_category();
$cat_id = $cat_id[0]->cat_ID;
$post_data[] = $cat_id;

$post_data = array_reverse($post_data);
$count_posts = 0;
$count_total = 0;

foreach ($post_data as $post_cat) {
if ($post_cat != 429) {
if ($count_posts == 6) {
} else {

return $offset - $count_total;

People who looked through the code will realise that we passed the do_not_terminate variable to WP_Query that we set up when addressing Problem 1. This is required because if we didn’t, we won’t get 15 posts into the future, instead we’ll just get however many posts starting from 15 posts into the future that include 5 real posts – which is totally useless.

To finish off nicely we’ll edit our “newer posts” link to use this calculated offset in our index.php file, but only display when we have a proper offset to show and we’re not on the first page.

<?php if ($future_offset != 0 || !empty($offsetting)) { ?>
<a href="<?php echo $future_offset; ?>">Newer Posts</a>
<?php } ?>

Tada – all done! I hope that helped somebody out there, but if not at least I have it for archival purposes. If you’re using it, let me know how it goes!


Beware of Google.

gooburnsGoogle is, actually, one of my top three disliked companies. The other two are Microsoft and Adobe. Why I dislike Microsoft and Adobe is a post for another day, but today I would like to talk about Google. Believe it or not, I will explain this without ONCE saying any personal bad experiences with Google’s services.

Google has recently unveiled at a developer preview their new product “Google Wave”. If you have not yet read about this, or watched the introduction video available on their webpage, I suggest you click here to go there now, and watch it.

If you have heard of it, and if you’ve watched the demo, you will be amazed. Not only have Google come up with a killer product, they’re going to open-source it, and developers will have access to the most amazing resources to produce the most amazing web applications possible. If you’re still reading and you haven’t watched the video, please go watch the video first.

Right – so the question is, why, especially if it’s open-sourced, are you against Google?

Try to look at it from this perspective. At this moment, we have three main operating systems, Linux, Mac and Windows, each with desktop applications built to cater for the underlying system. You might prefer one more than the other, and thus the more popular ones get more applications built, developers move to develop on the platform, and when the developers move, most users don’t realise this, but it’s where the developers like to go that determines what will progress and ultimately be used by you regular folks.

Right. So it’s a bit stupid to have a lot of competing technologies, and it’s obviously better to have one uniform system that just works ™ for all. That’s why we start to depreciate older technologies, merge together technologies, define standards, etc to make desktop systems more integrated, etc. This is well seen in stuff like KDE, GNOME, etc.

However, Google’s seen something a lot of others have been blinded about. The web is the only cross-platform, standardised system that exists. So whilst Microsoft, Linux and Apple go and fight their differences, Google, armed with its existing monopoly in the search engine system (yeah, indexes the internet, nice one) decides to take over the internet.

Here’s where you roll your eyes. But I’m not joking. Allow me to explain.

Since nobody can actually own the internet, Google has managed to think up another way of doing it. The plan starts with creating a lot of “uncanny” web applications. The uncanny valley was a concept used to describe the point at which one’s appreciation of technology due to its advancement changed to disgust because the technology became too “humanoid”. Eg: a humanoid robot only gets so awesome until it starts look identical to you, and better too, and with a hidden flamethrower. When used in the context of web apps, this is where the website’s interface mimics that of a desktop application. Like, for example: Google Docs.

This impresses a lot of users really quickly, as it allows them to do what was only previously possible if the software was installed on the system instead anywhere around the world with an internet connection and with a decent browser.

…and then Google starts releasing web APIs and toolkits to allow developers to take advantages of the systems it has created. This sounds really good, until you think about what else Google is doing.

Google releases their web browser, Google Chrome. Google Chrome is a breakthrough in certain technologies, allowing separate processes per tab, and support for some seriously cool javascript, ajax, whatever. Google’s aim in Chrome is “to show what the web is capable of”, pushing the limits, etc. With this browser, users can experience the best in uncanny websites, hence all functionality of your average desktop application can now, actually be done right in your browser. Again, Google Docs is a perfect example of this. Don’t believe me? Why don’t you try Photoshop in your browser, right now.

Once Google has a place in the browser market, they have every right to start sticking in their own ideas into the new HTML 5 standards. Now Google has their arsenal to define exactly what the browser is capable of. Together with their existing web toolkits and demos on the amazing stuff that is capable, who wouldn’t be happy to oblige?

Well, nobody. Google has made it so easy for the average person to access all of these great features. Even though Google Sites is a complete joke for web developers, for Joe down the street who can’t spell out HTML to save his life, Google Sites is amazing.

So people start switching. Because the technology behind it, too, is so impressive, developers start switching. In the end, what we now have is in effect “an operating system right in your browser“. Or as one person in IRC put it, another layer to depreciate the coding layers below it. Soon we will not need desktop applications any more, and everything will be done on the web. (of course there are also technical implications about this, like what will happen to the rest of the programming languages)

No, the web is still just through one browser you say, it’s not at all useful like that.

Actually, what about Chrome running as separate processes? What’s the difference between that and different applications? All that means is that instead of running KMail, your notetaking application, Pidgin, IRC client, OpenOffice and feed reader, now you’ll be running 6 or 7 Chrome separated tabs (so they’re just like individual applications) connected to GMail, Google Notepad, GTalk, Google Docs and Google Reader. In fact, you can have *deep breath*

google_evilGMail, Google Notepad, Google Calendar, Google Docs, Google Talk, Google Reader, Google Contacts, Google Desktop, Google Gears, Google Maps, Google Earth, Google Sites, Google Books, Google Translate, Google Scholar, Google Medical Records, Google Directory, Google Groups, iGoogle, Google Adsense, Google Streetview, Google Sync, Google Android, Google Youtube, Google Analytics, Google 23andme, Google Lively, Google Dictionary, Google Voice, Google Feedburner, Google Chrome, Google Chrome OS, Google Public DNS, Google Go, Google Shopping, Google Checkout, Google Apps, Google News, Google Video, Google Blogspot, Google Finance, Google Sketchup, Google Orkut, Google Trends, Google Code, Google Picasa … and now Google Wave.

Every single thing to replace every single desktop application you’ll ever need save for some development tools. I swear I could actually live a year with only using Google Products.

So once people try to compete with the huge massive framework Google has created for itself, the only way to create competitive products is to either rebuild your own framework (which is likely to be extremely time consuming and impractical) or …. Use Google Toolkit and Google API and Google Code.

So even though Google doesn’t own the web, Google has taken over the web. It doesn’t matter if it’s open-sourced, if you have to use Google Toolkit to make anything decent, that’s “Google is here to define what can be done” for you. The ultimate czar of the Internet.

Welcome to the future, where nobody knows what “desktop application” means.

Edited Dec 09 to add 8 more Google products to the list.


A Little 21 Fun with C++.

Given the recent love I’ve shown to a great deal of languages, including but not limited to making a text editor with Python (Ssss!), challenging your manliness with LaTeX (what real men use™), and most recently a tribute to a great deal of languages that all mesh together in the most wonderful way in “How to Make a Website part 1 – The Environment“, I’ve decided it’s time to give C++ a chance to show itself on this blog.

When I decided to learn application programming (from web programming), I chose the languages Python and C++. Python for the ultimate rapid application development it can be used for, as well as the ease of syntax that should introduce the application programming concepts a lot quicker to me, and C++ for, well, it’s pure power. C++ can be described as the swiss-army-knife of a programming language … a decently low level language, strictly typed, nicely object orientated, efficient, and it’s actually compiled, unlike what I’m used to (oh my, what a spoiled generation I live in). Another reason being that C++ is the main language used in KDE development, of which I would like to contribute to someday.

Today, being a Friday, was the be-all and end-all of the week, where I enter my weekend early, and take a break from the ongoings in my life. Therefore, I decided to poke again into C++. Armed with nothing but with whatever little I remembered from the first peek at the language more than 2-3 months ago, the man pages, and general knowledge of language syntax (well, the syntax highlighter gave some clues), I decided to make myself a BlackJack game. Suffice to say that the process was pain-free, and within 15 minutes I was playing BlackJack!

It is, of course, a CLI app, but I don’t see why it shouldn’t be cross platform. However, since I don’t have a Windows computer I can compile it on, you Windows folks will have to do it yourselves. For the technophobes, I give you a screenshot (hahaha):


…and for the more logic inclined, well … a combination of basic common sense and mathematics should be enough for you to get the gist of what the code is doing. (It’s even commented for the hard of thinking) Take a look:

#include <iostream>
* Generate random number that represents a card (1-13)
int generate_card()
return rand() % 13 + 1;

* The AI will always have a card between 15-21. This will generate their card.
int generate_ai_card()
return rand() % 7 + 15;

* Let's play the game!
int main()
// This creates a random seed for rand() based on the time.


bool play;
int ai_card, my_card;
char x;

std::cout << "Welcome to a very simple BlackJack game to kill time.\n";

play = true;

// Get the AI's card.
ai_card = generate_ai_card();

// Get your first card.
my_card = generate_card();

std::cout << "You have " << my_card << " - (h)it or (s)tay?: ";

// Ask for a hit or stay.
std::cin >> x;

// If they have hit...
if ( x == 'h' )
// Generate a card, and add it on.
my_card = my_card + generate_card();

// Have they bust?
if ( my_card > 21 )
std::cout << "You got bust (" << my_card << ").\n";
play = false;
std::cout << "You now have " << my_card << " - (h)it or (s)tay?: ";
// If they stayed...
else if ( x == 's' )

// ... See who is bigger.
if ( my_card > ai_card )
// You WIN!
std::cout << "You won! (" << my_card << " vs " << ai_card << ")\n";
play = false;
// You have FAILED.
std::cout << "You lost! (" << my_card << " vs " << ai_card << ")\n";
play = false;
std::cout << "Please either type \"h\" to hit or \"s\" to stay: ";
while ( play == true );
// Some credits and stuff.
std::cout << "Thank you for playing Dion Moult's C++ BlackJack game.\n";
return 0;

Again, it amazes me how I can turn a quick 15 minutes of nothing into an entire blog post. Perhaps I should finish off one of my drafts and give you something interesting for once.


How to Make a Website Part 1 – The Environment

Creating a new website from scratch into the next killer web-app is always tough, but the journey there can always be a fun one, given that your workflow is right, you know what you aim to achieve, and you’ve got the right tools for the job. I’ve decided to document the creation of The E2 Project, which is basically the re-creation of E2.

During the documentation, I will also teach you the do’s and don’ts of website creation. These are often overlooked, and you’d definitely pick up a lot of tricks that normally take years of experience to develop.

Understanding the resources around you.

Here’s a list of useful resources for the impatient: HTML, CSS, PHP, MySQL, Javascript, Ajax, Free scripts (yes, really), stock images, SVN, Git, Mercurial, Image editing applications (The GIMP), text editors (Vim).

OK, firstly I’m going to talk about setting up your mental and physical environment before you start a project. A lot of people who don’t develop with computer more than often disregard this vital step, and end up rushing or making a mess of things. The first step is to make sure you know what you want your site to do. Will it be a blog? Will it be your online portfolio? Will it be yet another youtube clone? If you know what it does, you should also know what type of person will use it, and what features it should have. You need to be clear on what features it should have, as that’s the bulk of any web-app.

Assuming that you now know what your site is about and what features it will offer, it’s time to make sure you really know what’s going on. Has it be done before? If it has, what can you offer that other sites don’t? What can you learn from existing websites? Are there useful javascript or ajax snippets that can give your webpage that extra zing that makes it stand out? For example, people developing a personal portfolio website might be interested in Lightbox, as that’ll improve continuity on the site and remove layout restrictions. It also makes things look cooler in general. (yes, I really said that)

The next step is to know your limits. You will need to know HTML back to front. Sure, you can forget tags, but as long as you know they exist, that’s fine. As the saying goes, the great programmer doesn’t need to remember it all. There’s really nothing wrong with using cheatsheets. If you do know HTML, make sure you know how to validate it. If you’re epically extreme about this, make sure you can get XHTML 1.0 Strict validation on all your pages. It’s all about discipline, and in the end it helps with cross-browser functionality and compatibility with newer devices like mobile phones. Just take the extra step, and please, oh please, validate your code.

Do you know CSS? Do you use CSS? Any site nowadays should only contain semantic markup and use CSS to effectively seperate design from layout. No matter what you do, do not use tables for layouting. It’s bad. It’s evil. It causes the folks in the #css IRC channel to condemn you to heck. It’s good practice. If you’re unsure what I’m talking about, read this handy guide. Of course, also don’t forget to validate your CSS code.

Do you know PHP and MySQL? True, this isn’t the only way to make sites, but it sure is popular, and hell powerful. How good are you at it? Do you know OOP, do you know MVC (or other framework styles)? If you answered no to either one, take your time to go and re-learn PHP. You’ll might find you’ve been doing it all wrong. Don’t disregard that warning, really, take your time and re-learn what it is.

How big is the project? Do you need version control for it? It’s quite comon for people to dump version control for web projects, even individual ones, as it really makes the developing stage less confusing. If you don’t know what version control is, try search it up, then search up CVS, SVN, git, and Mercurial. You should try it out on your system, get familiar with it and perhaps use it in your next project.

Are you good at design? This does not necessarily mean you have to be a wiz at something like Photoshop (ewww) or The GIMP, there are some really simple designs that look amazing. If you do follow the “Create graphic image” -> “Slice” -> “Create web-app” workflow like most do, do you know how to use CSS in the slicing stage? Do you know how to create a design that won’t break in flexible layouts? Do you know how to solve the never-ending battles with CSS and IE? (Yes, all those dirty coding hacks that are so troublesome)? Do you have good stock graphics? Most disregard stock graphics, but they really add shine to the page. Have you considered web load-times and optimisation when designing? There are hundreds of things to consider, and over time all these things become natural.

Don’t underestimate planning and protoypes.

Don’t underestimate the importance of this step either due to the shortness of this section. User Interface is almost the most important thing that exists on a webpage. Don’t get me wrong, I’m not saying that your backends and server-side scripts aren’t going to do the trick too, it’s just that your site is going to be used. To be honest, change the splash image of any application, and even if you don’t add any new features, it already looks as though it’s had a bunch of action packed updates over the last version. You want to have a clear idea of several things:

  1. The homepage of the site. This is the very first page people see, and the most important of all. This is what gives them their first impression, this is the page that should explain what you do, why you exist, and how you can benefit the user in less than a minute. This will be the central template design (especially for large scale sites) that defines the organisational structure and navigation style used throughout. Do not ever be inconsistent with design.
  2. Your databases. Yes, that’s right. You want to know what’ll be stored, where it’ll be stored, what’s the best way to store it so it can be used efficiently. The word that must be drilled into your head is modularisation. (Not a real word, but we aren’t learning English here, are we?) Basically, you want to use it one way, and any way you might think of in the future. I’ll cover this in more detail when I talk about setting up databases later.
  3. The system and framework. Yes, I stress frameworks again. Too many a PHP script kiddy has spewed out nothing but spaghettic logic. It’s not a fate you deserve. What framework are you going to use? Build your own? Use a preexisting one? Any needed libraries? How should you divide the logic framework into modules?

Work, flow. Work!

The third and last topic I will cover in Part 1 of this series is workflow. This is VITAL. Read that again. That’s the acronym for Very Important Topic Aids Learning. I won’t go into much detail, because all my next parts will focus on workflow too. Some thing you might have noticed here. I did not mention servers or domains. That is NOT your concern. Too much worrying about servers and domains will leave you with a crappy system that’s up 100% of the time. Which nobody wants. You need to make your site? Need a server? Install Apache on your localhost and build it there. Don’t waste money on a

Workflow is amazingly flexible, but there are some one-size-fits-all that works. The first thing you want to get out of your way is the environment stuff I talked about in the first topic I covered. Know back to front what’s going on and how it’s going to go on. Assuming you have that all worked out, you’d want to create a design using an image editing program. Even if your site is something like Google or Yahoo that has a high text:image ratio, you want to visualise it first. No point playing around with CSS if you haven’t got a clear image in your head. Once you’ve got your visualisation done (good for the home page), create a valid HTML and CSS slice of the page. Split it up into template files and start organising and creating dummy filesystem structures in your framework. Create a couple static non-dynamic pages just to check the flexibility of the layout (stretches, different tags: forms, inputs, divs, headers), check cross-browser compatibility, and then when you’re done, make the home page and fill it with placeholders as necessary.

Now you can start working on the actual logic and system of the website (excluding previous framework setup). The first step is to create all your needed database tables, and choose the appropriate field types and set values. After this, since I use an MVC framework for most of my sites, I like to work pretty much … in that order. I build the models first, build the views, then just connect everything beautifully with the controllers. I generally like to start with building the user system, which is often the key and wire system of a website. This covers easy stuff like database input, form building, error and message templates, and general usability of the site. It’s the perfect “mini-system” to test the effectiveness of your framework, templating system, and helper libraries.

It all pretty much spins off from there, before venturing to code debugging, stress and user testing, hacking preventation, and advertising. Website creation is a huge topic, and unfortunately a text-heavy one too. Hopefully I’ll write part 2 soon!


A Little Python Fun

When I last touched Python, I wrote a snippet to steal the latest comic off Like most of the things that I do (this only applies to individual projects, not teamwork), there are long breaks until I make any progress. Probably it’s because I multi-task too much. At the same time, I never run out of things to do. Recently I’ve been blessed with a couple hours of fre etime, and so I’ve touched Python again, and decided it was time to learn some GUI.

Which toolkit? The Qt one of course (pronouned ‘cute’)! Powerful, cross-platform, native to KDE. Here’s my first (well first mentionable) GUI application coded with Python and the PyQt4 bindings. (Last mentionable GUI stuff was with VB6 – Yes, I did do application programming when I was 9 years old, childish programs they were, but mentionable).

The application is a simple text editor which supports opening/saving files, and warns you if you’ve made changes but haven’t saved yet. Yes, the process of making it was from a tutorial, though each step was figured out myself. Basically the tutorial says “Ok, now we’ll add a save button”, then I search the Python and PyQt4 documentation to figure out how, then cross reference my code with the tutorial. Here’s a screenshot:


For the geeky, here is the code:

import sys

from PyQt4 import QtCore, QtGui
from editor import Ui_notepad

class StartQT4(QtGui.QMainWindow):

  def __init__(self, parent=None):

    QtGui.QWidget.__init__(self, parent)
    self.ui = Ui_notepad()

    # Connect signals

    QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog)
    QtCore.QObject.connect(self.ui.button_save,QtCore.SIGNAL("clicked()"), self.file_save)
    QtCore.QObject.connect(self.ui.editor_window,QtCore.SIGNAL("textChanged()"), self.enable_save)

  def file_dialog(self):

    response = False

    if self.ui.button_save.isEnabled() and self.filename:

      message = QtGui.QMessageBox(self)

      message.addButton('Save', QtGui.QMessageBox.AcceptRole)
      message.addButton('Discard', QtGui.QMessageBox.DestructiveRole)
      message.addButton('Cancel', QtGui.QMessageBox.RejectRole)
      message.setText('Do you want to save changes?')
      message.setDetailedText('Unsaved changes in file: ' + str(self.filename))


      response = message.clickedButton().text()

      if response == 'Save':


      elif response == 'Discard':


    if response != 'Cancel':

      fd = QtGui.QFileDialog(self)
      self.filename = fd.getOpenFileName()

      from os.path import isfile

      if isfile(self.filename):

        plik = open(self.filename).read()


  def file_save(self):

    fd = QtGui.QFileDialog(self)
    self.filename = fd.getSaveFileName()

    from os.path import isfile

    if isfile(self.filename):

      plik = open(self.filename, 'w').write(self.ui.editor_window.toPlainText())


  def enable_save(self):


if __name__ == "__main__":

  app = QtGui.QApplication(sys.argv)
  myapp = StartQT4()

Tada. You will also need another file called (click to download) in the same directory from which the UI information will be grabbed from.

Ok, next Python project will be more advanced, which’ll be a graphical game of solitaire featuring custom widgets and drag and drop functionality. Oooh. Tough.


Learn how to make a basic website framework.

This will teach you how to setup one page for all pages! So it’ll be a lot easier when changing layouts!
Not only that, say GOODBYE to /index.php?page=contact…now you can just have /contact without actually making the directory!
This will ALSO teach you how to have a site which you can easily switch version (like when running parallel systems) when you are working on a new version and you don’t want others to know. It will have password protection which will allow only authorized users to test the version.
Say goodbye to “coming soon” pages!

Ok, first we want a layout…Let’s be simple (just forget validation temporarily, this just an example):

My title.<br />
<a href=””>Home</a><br />
<a href=””>asdf</a><br />
content will go here<br />

Let’s save that file as index.php. Save it in a directory called “versionname” (you can change this, but remember to change the rest of the code as well) Now, replace “content will go here” with this:

if($page == “”) {
include “/home/username/public_html/versionname/home.php”;
} elseif($page == “asdf”) {
include “/home/username/public_html/versionname/asdf.php”;
} else {
echo “error”;

Basically, it will see what the value of the variable $page is and accordingly, it will display the correct page.
Create a new page called home.php (you can put whatever you want in it), and save it in the “versionname” directory. Then create a new page called asdf.php and put whatever you want in it and save it in the “versionname” directory.

Now try and go to It will display your home page. Then go to It will display your asdf page. Let’s say in the future you decide to change your layout…you only need to change one page…the index.php page.

Ok. now instead of ?page=asdf, lets turn it into just /asdf. Go into your public_html folder (or your equivalent of it) and search for .htaccess. Open it up. This is apache server scripting. Won’t go into much detail though. You’re probably annoyed because you want your homepage to be in and not Simple, add this code in .htaccess:

RewriteEngine on
RewriteBase /

ReWriteRule ^/$ versionname/index.php
ReWriteRule ^$ versionname/index.php

Now, try to go to Amazing! The URL didn’t even change! Now to change into /asdf. add this:

ReWriteRule ^asdf/$ versionname/index.php?page=asdf
ReWriteRule ^asdf$ versionname/index.php?page=asdf

Now, go to Amazing! It showed the ?page=asdf page!
Ok, now that you’ve done all that, let’s say you want a new version, but you don’t want to delete everything and setup a coming soon page. Create your new version in a directory called “versionname2”.
Now, you want people to be able to access your new version, but not all people. So here’s what you do. Add this to the top of your versionname (not 2) index.php:

header(“Cache-control: private”);
if( $_POST[beta] ) {
if( $_POST[pass] == “yourpassword” ) {
$_SESSION[“beta”] = “1”;
if( $_SESSION[beta] == 1 ) {
include “/home/username/public_html/versionname2/index.php”;
} else {

And now, add the form below to wherever you want the verification to be:

<form method=”post” action=””><br />
<input name=”pass” type=”password” class=”input”>
<input name=”beta” type=”submit” value=”betatest”>

So now, when you type in the password “yourpassword” in the form, you will be browsing your new version, with no edited URLs! Of course, to make it fully compatible you need to add the if $page=”” statements to your versionname2 index.php, but that’s simple to do.
Ok, you’ve finished coding your new version. Simple, just go to your .htaccess, and replace all the /versionname to /versionname2. Done! You’ve succesfully upgraded your site.

Note: this is very basic but I hope it has helped some of you.