Photo
Michael Duerinckx
is a (mostly front-end) web developer for Carswell Gould. Other than web development he is into electronics design as well as music production.
All content by Michael Duerinckx unless mentioned otherwise.

Posts in ‘Coding’

MVC – FuelPHP

Since I started working at Carswell Gould, I’ve learnt a lot more about web development—It’s amazing how much you learn once you start collaborating with other people—and among those things I learned is how to work with the MVC (Model-View-Controller) design pattern. The way I used to work was just by having the database operations inside classes as much as possible, and use those classes and their methods in the files for the actual pages. For example, A forum thread page (view.php or similar) would have all the code to load the posts and relevant info above the HTML part of the file, using classes like ForumThread and the like.

The MVC way to go for this would be having a controller that gets called when the URL for viewing a thread is requested. The controller would get an instance of a ForumThread Model. The Model describes the properties of a ForumThread and deals with related data (Forum posts, which would be another Model), and database operations, plus any additional behaviours. The data retrieved from the Model instance then gets passed on to a View, which takes care of sticking all the data in HTML. This way interpreting the request, dealing with data and displaying data is nicely separated.

Frameworks (FuelPHP)

This whole design pattern is all a very beautiful way to structure your web applications, however, if you have to set that all up from scratch, it would get very tiresome to get right. That’s where frameworks come in. The first PHP framework I got in touch with is FuelPHP, a quite young framework running on PHP 5.3+. According to their front page, it is based on the best ideas of other frameworks, with a fresh start. As this is the first framework I’ve used, I can’t really judge that former part, but by googling certain concepts used, I’ve found out that many of them are quite commonly accepted ones.

In my experience, it’s very simple to set up some new models and relate them, to quickly get going without all the design hassle you’d normally have. For the most part, you don’t get to write the database queries yourself, which is a good thing.

Validation

An unrelated part of FuelPHP (as in, it doesn’t really have anything to do with MVC) is its validation functionality. FuelPHP makes it really smooth to validate input. There are multiple ways to go for it, but my preferred way is to actually specify the validation rules in a Model’s properties array, then setting up a Validation Observer before save.

If that sounded confusing: An observer is a class that has a number of event-named methods. In a Model you can refer to an observer class and tell it which events to observe. FuelPHP takes care of the rest: When you let your model save its data to the database, any observers with ‘before_save’ enabled will be executed first. In the case of a Validation observer this will first run all the validation rules specified in the properties set-up, and throw an error (preventing the actual database save) in the case that some data does not validate.

Having gone through setting up a whole bunch of nested ifs for data validation in the past (Believe me, it’s tiresome and not elegant at all), I find this way of setting up validation simply beautiful. It’s all down to adding a few strings to an array, and it’ll validate. The way the framework is built allows for easy adding of your own validation functions too, so other than elegant, it’s very flexible.

Adopt FuelPHP!

Currently, the community surrounding FuelPHP is still fairly small, which means it’s often quite hard to google FuelPHP-related things. I would very much like the community for this framework to grow, as I feel it has a lot of potential. Their website (mostly docs section) is still quite incomplete in places, but that should improve as the community grows.

More information

I’ve only briefly touched upon many subjects in this post, so if I sparked your interest, these couple of links should get your started.

Obviously, if you are really interested in trying it out, I suggest downloading it and playing with it! You can get support on their forum and in their IRC channel.

MySQL: find number of matches in another table

The problem of finding the amount of matches in another table is one that had me stumped for a while, but after googling a while, looking through concepts that were new to me, I figured it out. Since it may be a fairly common problem, I thought I’d share my solution here.

Use cases

I used this technique to find the amount of posts a user has on a forum, in a situation where I have a users table, and a forum table. Other possibilities could be amount of sales for a certain item in a webshop, where the items are in a table, and the sales in another. I’ll use the users / posts example to show the query.

Users table

user_id username
1 Mich
2 John
3 CornCob

Forum table

post_id user_id topic_id message
142 1 54 Pellentesque posuere…
143 3 42 Cras sodales molestie…
144 3 54 Phasellus condimentum euismod…
145 1 65 Aliquam placerat nibh ut…
146 3 54 Donec nec convallis…
147 1 54 Sed tincidunt fermentum…
148 1 60 Aenean id turpis…

The query

SELECT
  users.user_id,
  users.username,
  COALESCE(pc.postcount, 0) AS postcount
FROM
  users
  LEFT JOIN
  (
    SELECT
      forum.user_id,
      COUNT(forum.post_id) AS postcount
    FROM forum
    WHERE 1
    GROUP BY forum.user_id
  ) pc ON pc.user_id=users.user_id
WHERE 1

How it works

First, we select the information of the users, simply, by referring to them using table.field. Then, we also include a postcount field, but not quite like we’re used to seeing it. Since the value ‘NULL’ would be retrieved for users who don’t have any posts, we have a workaround. The COALESCE function returns the first non-NULL argument it is given. So if there is no match for a certain user_id in the table ‘forum’, the resulting NULL will not be used, we get a regular numeric 0 instead.

The simple user information is retrieved, as expected, from the users table. After that it gets a little more tricky. We perform a LEFT JOIN with what is called a subquery. Within the parentheses after ‘LEFT JOIN’, there is a whole new query; the resultset of this query will behave itself as another table we’re joining.

In our subquery we select the user_id and postcount. Normally, using COUNT() this way would simply return a single result, with the amount of rows in the whole forum table. However, because we’re using ‘GROUP BY forum.user_id’ here, it will count the postcount for each unique value of user_id encountered in forum. This gives us a simple user_id, post count table as a result.

Now we’re outside the parentheses again. The ‘pc’ you see after the parentheses is the name we assign to the resultset of our subquery. We can refer to it as if it were any regular table, as we see in the SELECT part of our main query, as well as the ON part we’re at now. We want to join the two table where the user_id’s match, again, like any regular join. In case there is no match for a user_id from the table ‘users’, there would be no corresponding postcount value to join in the final resultset, thus, a value of NULL is given, which is then ‘changed’ to 0 by the COALESCE function.

The resultset

Here you see what the outcome of above query would be on our given tables:

user_id username postcount
1 Mich 4
2 John 0
3 CornCob 3

Please note

This was all tested and figured out on MySQL 5+. Thus, I don’t know if it would work on other SQL servers. As far as I know, the IFNULL function is the one thing that’s usually different throughout database servers. The subquery system will mostly be the same-ish.

If you know more about this, or I’m misinforming on anything, please, by all means, let me know in the comments and I’ll change it up to be as accurate as possible.
Also, if you know a more efficient way to go for this specific task, let me know as well. Obviously, feel free to ask any questions if something is unclear.

Updates

April 23rd, 2011: Changed the IFNULL to the standards-compliant COALESCE function – thanks Omar.

April 30rd, 2011: Fixed the query: COUNT(forum.postIDpost_id) AS postcount – Thanks Ringish.

Minecraft design tool

TL;DR: I made this thing: Minecraft design tool

My girlfriend bought me the ever-so-popular indie game ‘Minecraft’ for my birthday, even though I kept saying I would never play it. I tend to get obsessive over certain thing; mostly things that involve creating, building, which is all Minecraft is about. After having seen her play it for quite a while however, I decided to give it a go anyway, as it looked like far too much fun to be left alone. As expected, I did start to obsess over it, once I got everything down properly (which was rather soon since the game is really easy to play).

Since Minecraft also has a multiplayer mode, my girlfriend and I were soon playing together in our own virtual world. After a while we started building things together, which was and still is endless fun. However, when you just explain your idea of what you want to build, there sometimes is a bit of miscommunication, and one or the other starts building things in a way that wasn’t intended, because they misunderstood. Needless to say, this happened a couple of times, with mutual frustration as a result.

A simple drawing on a grid can greatly help explain what you mean, I thought; thus, I got to work. I decided to quickly throw together a tool that lets you draw things in 2D, with Minecraft material sprites. I built it with the tools I’m most experienced with; namely HTML, CSS and JavaScript.

ScreenshotThe tool simply uses a table as its grid. I realize that a drawing isn’t quite tabular data,  but it seemed the best way to go for it. Since I used HTML5 to make it, I know I could just have used the <canvas> tag, but I’m afraid I don’t have quite enough experience with that one to build something with it quickly—which was mostly the goal here. That and the fact that canvas is one of the things that can’t really be used in older browsers, so it would effectively NOT work there, made me decide to use a table.

I kept the tool very simple and to the point, because all I really wanted was a quick design tool that let you share your designs with others. It isn’t quite the prettiest as it is, but it’s functional, and that’s what matters… to me, at least.

The first version I put up did not have a save button, as it was pure HTML, CSS and JavaScript. To share a design, you had to use the export function, paste the exported data (which is in JSON-format, for those interested), copy the output to your Minecraft partner(s), and have them import it again. Since this is a rather tedious way of sharing designs, I built the PHP part later, which saves a design under an 8-character ID. This way, you can just copy an url the conventional way, and the design will be loaded straight away. For those who still have an exported design sitting around somewhere, you can still import it and save it online.

Seeing as there is no account system or anything, you can’t save to the same ID; you always save to a new one. This prevents people from vandalizing others’ designs. (Or griefing, if you prefer the popular Minecraft term).

Future ideas

Since I made a PHP part for it, I’m planning to expand on that. One nice idea I have is to build an actual image generator; PHP would simply combine the sprites into a single image and make it available for download as a PNG.

Another handy feature would be to have a little list of latest designs, so you don’t need to bookmark everything. I might use a cookie to have a list of the latest designs you made, which makes it easier to find your own designs, rather than just the latest few. I’ll keep you updated.

JavaScript: getChildNodesByTagName()

Posted on: 4 Comments

If you’ve ever used JavaScript’s getElementsByTagName(), you may have noticed something annoying about its behaviour. (Well, it’s only annoying depending on your application.)

getElementsByTagName returns every element matching the tag name given, regardless of its position in the document tree. This is annoying if you only want to use the elements that are direct descendants of the element you’re calling it from.

So anyway, to cut this short, I wrote  a quick but effective function that works just the same as getElementsByTagName, with the difference that it only returns direct descendants. Just add in this snippet of code and you can start using the function just as you would use getElementsByTagName.

Object.prototype.getChildNodesByTagName = function(tagName) {
    var byTagName = this.getElementsByTagName(tagName);
    var outArr = [];
    for(a=0;a<byTagName.length;a++) {
        if(byTagName[a].parentNode == this) {
            outArr[outArr.length] = byTagName[a];
        }
    }
    return outArr;
}

Here’s how it works:
The function uses the typical getElementsByTagName, and then iterates over all the elements found. For each element it checks whether the element’s parentNode equals this, which is the node that should be the parent of any elements we want to return.
When the comparison is positive, the element is added to the array, which is later returned.

I hope you can put it to good use!

Leave me a comment if this was helpful to you, or if there’s anything wrong, please.

The Audio Portal

Well, the secret project has been out for nearly a month now. It is named “The Audio Portal” and can be found here: http://theaudioportal.com.

That’s right, I’m only now getting around to make a blog post about it. TAP, as I like to call it, has been in development since August 2009. I’ll admit, the site was inspired by Newgrounds. As if it wasn’t obvious yet. Over the 2 years I’ve been active in the Newgrounds audio community, I kept hearing about the same problems with the system, as well as experiencing them personally.

We all (we being the active community) realized that complaining about it wasn’t going to fix the problems we experienced, instead, we frowned upon forum topics regarding so-called “zerobombing”, or topics about missing genres and so on. I felt that there should be something like Newgrounds, but focussed just on music.

(more…)

PHP class: Page control

Time for my first coding-related post!

Whenever I was coding something in php, and I had to make something with a page control, I started procrastinating, because I was always looking up against figuring that stuff out again.

I decided to get that over with for one and all, and wrote this page control class that allows me to create a new, fairly customizable page control, which can even be used to interact with the code that loads whatever needs to be displayed on the page.

It is only the first version, which only allows for one type of page control (the typical first, previous, next, last controls), but I’m planning to make it do different types in next versions. Anyway, that’s enough rambling, it’s time for some code. (more…)