An alternative for SQL pagination

I was reading up on improving the performance on MySQL when I found an article and stumbled on a really cool alternative to using offset when generating pagination results from the database.

On the query side, instead of using LIMIT with offset, you can select one more row than you need, and when the user clicks the “next page” link, you can designate that final row as the starting point for the next set of results. For example, if the user viewed a page with rows 101 through 120, you would select row 121 as well; to render the next page, you’d query the server for rows greater than or equal to 121, limit 21.

Source: http://www.infoworld.com/d/data-management/10-essential-performance-tips-mysql-192815?page=0,1

Building a template engine in PHP

Possibly the most common sign of bad code is tight coupling, especially between logic and presentation. It might seem like a good idea to print out the HTML while the data is being generated, but it more often than not leads to a big incoherent mess of tangled code. It also causes other issues, like what happens if an unexpected error occurs in the middle of the page? By then half the page has already been outputted and it might be too late to handle the error nicely.

There are a lot of problems with mixing logic and presentation, but it’s actually very easily solved, especially in PHP. While PHP makes it unnecessarily easy to write shitty code it also provides a lot of ways to avoid it. I’ll use this post to show you how ridiculously easy it is to create a template engine in PHP in three easy steps.

So, we begin by setting up a simple class to wrap our template. The $template variable passed in the constructor is the relative path to our template, e.g. if the templates are in a folder called “views” you should pass “views/.php” to the constructor.

class Template
{
    protected $template;

    public function __construct($template)
    {
        $this->template = $template;
    }
}

Then we add variables to it, we use magic getters and setters for this to make handling of our template a little more verbose, but you can of course use regular getters and setters if you prefer that.

class Template
{
    protected $template;
    protected $variables = array();

    public function __construct($template)
    {
        $this->template = $template;
    }

    public function __get($key)
    {
        return $this->variables[$key];
    }

    public function __set($key, $value)
    {
        $this->variables[$key] = $value;
    }
}

Lastly we add the printing of the template, this abuses some pieces of PHP’s functionality. Partly that code can be included anywhere and that all the output can be stored and loaded into variables. We load all created variables into the functions variable scope with extract(), this has the nice side effect of not conflicting with variables created outside the function and limiting the template file’s access to variables created in the template. Also, by using chdir() before including the file, we change the working directory to the specified template directory (if any). This allows for including other templates within templates without having to concern ourselves with where the template will be loaded from.

public function __toString()
{
    extract($this->variables);
    chdir(dirname($this->template));
    ob_start();

    include basename($this->template);

    return ob_get_clean();
}

We can then use it anywhere we want like this. Of course, if you actually need functionality like this you might have more use for a template engine like Twig, which is a bit more extensible and comes with a ton of cool features.

$view = new Template("path/to/template.php");

$view->title = "Hello world!";
$view->description = "This is a ridiculously simple template";

echo $view;

Bear riddle

I love riddles, this is probably my favorite one since it seems very irrational but is pretty easily solved by logical deduction. Can you solve it?

A bear walks one mile south, one mile east and one mile north and is then back at its original position.

What color is the bear?

How to combine multiple commits into one

If you’re using Git you know how powerful it is as a CVS tool. But when Git is used as a deployment tool to be able to quickly revert changes if needed it may cause some headaches when deploying major features. There’s a trade off between having one giant commit and working with Git the preferred way of using small, incremental commits when deploying in this way. If there’s a critical problem with the new feature it will need to be reverted quickly which could become quite annoying if there are a lot of commits. While on the other hand it more or less defeats the purpose of using a CVS if you’re never working with your history, so to solve that I present the wonderful part of Git that is known as rebasing.

By enabling Git’s interactive mode with git rebase -i [commit] we can interactively specify what we want to do with each commit. [commit] should be which commit you wish to rebase to, that is to say, the specified commit will not be included in the rebase. You can also specify how many commits from HEAD you wish by instead of inputting the hash, subtracting the number of commits you want from HEAD with a tilde like so HEAD~5.

This should open up your text editor with the list of commits you’ve chosen and their messages.

pick b386745 Backed changes as they broke the autoloader
pick 385d14b Added precautions to model
pick 96aec4c Updated datamapper
pick 77fc647 Added isset to models
pick 7ac5e2d Added newline to main controller
pick 1a0a08b Cosmetic updates
pick 7a35bfa Re-added file_exists()
pick 2e98b00 Added ordering to database abstraction layer

As you should see, they’re sorted in reverse chronological order. Pick means that it should use the commit, if you let the first commit stay as pick and change the others to squash all the other commits will be joined into the first one. After this you need to write a new commit message for the new squashed commit which defaults to all the previous messages after each other and then you’re done!