20
Sep '14

by john

I’ve been writing a system recently which does a lot of classic CMS functions, including creating and maintaining assets (these could be new items, marketing information or whatever) which need to be version controlled.
Each asset will have a unique reference, so to pull out the latest versions of each asset I need to do a subquery join, grouping on the reference, the SQL being along the lines of:

select assets.* from assets
inner join (select assets.reference, max(assets.created_at) as created_at from assets group by reference) as most_recent
where assets.reference = most_recent.reference and assets.created_at = most_recent.created_at

Now that’s not the simplest of SQL but it’s reasonably understandable to most of us. However try and translate that into Laravel’s query builder and you’ll have some troubles. It doesn’t like subqueries at the best of times, but when you try to make it join on a subquery then it has a complete meltdown! However after a lot of trial and error I’ve found a way:

$sub_query = \DB::table('assets')
    ->selectRaw('assets.reference, max(assets.created_at) as created_at')
    ->where('assets.active', true)
    ->groupBy('reference');

return Asset::select('assets.*')
    ->join(\DB::raw('(' . $sub_query->toSql() . ') as most_recent'), function ($join) {
        $join->on('assets.reference', '=', 'most_recent.reference')
            ->on('assets.created_at', '=', 'most_recent.created_at');
    })
    ->mergeBindings($sub_query)
    ->get();

Good grief that took some figuring out!

29
Aug '14

by john

I can’t believe it. I’ve just been convinced of a valid use-case for the ‘goto’ statement. I never ever thought this could happen, and admittedly it’s only really valid in procedural languages that don’t have built-in error or exception generation/handling. Yet still, for those PHP1 and POP11 programmers out there, here it is.
The valid use-case is emulating exception generation in a procedural environment. If ‘goto’ is used to trigger a terminal action as an exception within procedural code it actually kinda makes sense. The key point is the action being terminal (i.e. the last thing that happens before you exit) and there being no better built-in way of doing it.
From wherever you are in your code, if something goes wrong and you want to throw an exception then you are effectively jumping out of the normal flow, spitting out your exception and exiting. ‘Goto’ can achieve this within procedural code reasonable well and safely.

function thisIsMyFunction($this_is_a_var = false) {
     if($this_is_a_var) {
          //Happy path
     }
     else {
          goto exception;
     }
}

exception:
echo 'Well something went wrong there!';
exit();

Obviously that example was in PHP which is no longer a procedural language, but you get the idea.

I still haven’t found any good reason to use ‘eval’ though…

10
Aug '14

by john

Bit of a fun one this time. I was having a look at some of the Stack Overflow Code Golf challenges and stumbled upon this challenge to make scripts that generate mathematical art in 140 characters or less, the idea being that you could tweet them if you so desired.

The code was mostly in C or C++ but I can read it well enough to transpose a couple of the best ones into PHP. The following to are examples of fractals; a Mandlebrot set and Julia set respectively and I think they’re amazing mathematically and beautiful aesthetically. I won’t post the generated images themselves as then you’ll miss out on the coolness of generating them yourselves. It staggers me that you can create such awesome images with so few lines of code.

Mandlebrot Set Fractal

ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);

header("Content-type: image/png");

$dimension = 1200;
$y_offset = $dimension / 2;
$x_offset = 3 * ($dimension / 4);

$im = @imagecreatetruecolor($dimension, $dimension) or die('Cannot create image');

for($x = 0; $x < $dimension; $x++) {
    for($y = 0; $y < $dimension; $y++) {
        $k = find_k($x, $y);
        $red = red($k);
        $green = green($k);
        $blue = blue($k);
        $colour = imagecolorallocate($im, $red, $green, $blue);
        imagesetpixel($im, $x, $y, $colour);
    }
}

imagepng($im);
imagedestroy($im);

function red($k) {
    return $k > 31 ? 256 : $k * 8;
}

function green($k) {
    return $k > 63 ? 256 : $k * 4;
}

function blue($k) {
    return log($k) * 47;
}

function find_k($i, $j) {
    global $x_offset, $y_offset;

    $x = 0;
    $y = 0;
    $k = 0;
    $big_x = 0;
    $big_y = 0;

    while($k++ < 256 && ($big_x + $big_y <= 4)) {
        $y = 2 * $x * $y + ($j - $y_offset) / $y_offset;
        $x = $big_x - $big_y + ($i - $x_offset) / $y_offset;
        $big_x = $x * $x;
        $big_y = $y * $y;
    }

    return $k;
}

Julia Set Fractal

ini_set('max_execution_time', 0);
ini_set('max_input_time', 0);

header("Content-type: image/png");

$dimension = 1024;

$im = @imagecreatetruecolor($dimension, $dimension) or die('Cannot create image');

for($x = 0; $x < $dimension; $x++) {
    for($y = 0; $y < $dimension; $y++) {
        $k = find_k($x, $y);
        $red = red($k);
        $green = green($k);
        $blue = blue($k);
        $colour = imagecolorallocate($im, $red, $green, $blue);
        imagesetpixel($im, $x, $y, $colour);
    }
}

imagepng($im);
imagedestroy($im);

function red($k) {
    return 255 * pow(($k - 80) / 800, 3);
}

function green($k) {
    return 255 * pow(($k - 80) / 800, 0.7);
}

function blue($k) {
    return 255 * pow(($k - 80) / 800, 0.5);
}

function find_k($i, $j) {
    $x = 0;
    $y = 0;
    $k = 0;
    $big_x = 0;
    $big_y = 0;

    while($k++ < 880 && ($big_x + $big_y <= 4)) {
        $y = 2 * $x * $y + ($j * 0.000000008) - 0.645411;
        $x = $big_x - $big_y + ($i * 0.000000008) + 0.356888;
        $big_x = $x * $x;
        $big_y = $y * $y;
    }

    return $k;
}

The algorithms are not my invention and I make no claim to them. I transposed them to PHP, added the image generation code and did a few optimisations but the core mathematical formulae were produced by much smarter people than myself!

11
Jul '14

by john

Fluent, also known as chaining, is a very simple design technique to help clean up the way you call your functions within objects. It’s a very simple concept, and supported by many of the big frameworks, but is surprisingly under-used out in the wild.
Basically, the idea is that with every function call that isn’t designed to return a specific response (i.e. setters rather than getters) returns the parent object.
As an example, imagine you had a ‘Person’ object where you could had setters for the name, age and height. In the non-fluent world you might have some code that looks like this:

$person = new Person();
$person->setName(‘John’);
$person->setAge(33);
$person->setHeight(‘6 feet’);

But in the fluent world you could do the following:

$person = new Person();
$person->setName(‘John’)->setAge(33)->setHeight(‘6 feet’);

And all that is needed to be able to use fluent calls is to change functions such as this:

public function setName($name) {
                $this->name = $name;
}

To this:

public function setName($name) {
                $this->name = $name;
                return $this;
}

Much nicer I’m sure you’ll agree!
Of course proper code ninjas would generally use the __call method to handle setting and getting without the need to define individual functions for individual fields but the principle will still work there, just return $this when you’ve done your logic and you’ll be living in the fluent world.

02
Jun '14

by john

I’ve been having a go at pulling server information and stats out of PHP as a ‘nice to have’ for an application I’m building. It turns out that you can retrieve a fair bit of information from a Linux system if you’re not afraid of wrapping a few system calls. Here’s my finished script, please feel free to use at will!

$stats = array(
    'Host Name' => exec('hostname'),
    'System Date/Time' => date('Y-m-d H:i:s')
);

$uptime_parts = explode(' ', file_get_contents('/proc/uptime'));
$uptime_raw = $uptime_parts[0];
$days = floor($uptime_raw / 86400);
$hours = ($uptime_raw / 3600) % 24;
$minutes = ($uptime_raw / 60) % 60;
$seconds = $uptime_raw % 60;

$stats['Uptime'] = $days . ' day(s), ' . $hours . ' hour(s), ' . $minutes . ' minute(s) and ' . $seconds . ' second(s)';

$load_parts = sys_getloadavg();
$load_average = $load_parts[0];

$stats['Load Average'] = $load_average;

$memory_data = preg_split('/[\r\n]/', file_get_contents('/proc/meminfo'));

if($memory_data && count($memory_data) >= 2) {
    $memory_total_parts = array_values(array_filter(explode(' ', $memory_data[0])));
    $memory_total = number_format(($memory_total_parts[1] / 1000000), 2);
    $memory_free_parts = array_values(array_filter(explode(' ', $memory_data[1])));
    $memory_free = number_format(($memory_free_parts[1] / 1000000), 2);

    $stats['Total Memory'] = $memory_total . ' GB';
    $stats['Available Memory'] = $memory_free . ' GB';
}

$stats['Total Disk Space'] = number_format((disk_total_space('/') / 1000000000), 2) . ' GB';
$stats['Available Disk Space'] = number_format((disk_free_space('/') / 1000000000), 2) . ' GB';
19
May '14

by john

“Whoa there! Don’t cross the streams!” I hear you cry, and I don’t necessarily disagree with you. Passing by reference is second only to eval* and goto* calls with its ability to reduce decent code into an impenetrable forest of obfuscated chaos. However, when used with restraint, in certain circumstances passing by reference can be a very useful tool.

Consider for a moment you are writing a user management tool and, in the best ORM fashion, you are making your controller as thin as possible and getting all of your business logic into your models. You might have an add user action that looks something like this (examples are in RESTful Laravel ‘cos it’s awesome):

public function store() {
    if($input = \Input::all()) {
        if(\User::create($input)) {
            \Session::flash('success', 'User added');
            return \Redirect::route('user.index');
        }
        else {
            \Session::flash('error', 'Could not add user');
            return \Redirect::route('user.create')->withInput();
        }
    }
    else {
        \Session::flash('error', 'No input given');
        return \Redirect::route('user.create');
    }
}

So that’s about as thin as we can make a controller, but we have no field validation here and it’s not very intelligent. So what if we overrode the model’s default create method:

public static function create($input) {
    $rules = array (
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|email'
    );

    $validation = \Validator::make($input, $rules);

    if($validation->passes())
        return parent::create($input);
    else
        return false;
}

It’s better but we still don’t have our validation messages being passed back. Now there are three options from this point; we can move our validation into the controller (less than ideal as it bloats our controller), we can have some sort or logic where you get a boolean value back from the model if validation passes or your array of error messages if it fails (which takes some figuring out once we get back to the controller), or we can pass our error messages back out of the model by reference:

Controller:

public function store() {
    if($input = \Input::all()) {
        if(\User::create($input, $messages)) {
            \Session::flash('success', 'User added');
            return \Redirect::route('user.index');
        }
        else {
            \Session::flash('error', 'Could not add user');
            return \Redirect::route('user.create')->withInput()->withErrors($messages);
        }
    }
    else {
        \Session::flash('error', 'No input given');
        return \Redirect::route('user.create');
    }
}

Model:

public static function create($input, &messages = array()) {
    $rules = array (
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|email'
    );

    $validation = \Validator::make($input, $rules);

    if($validation->passes())
        return parent::create($input);
    else {
        $messages = $validation->messages();
        return false;
    }
}

Here we have the best of both worlds; we’re returning a boolean to indicate success or failure, but we have also passed our validation messages back by reference. As such, if validation failed we are able to send the validation messages back to the view without introducing any additional business logic or bloat to the controller.

* Don’t ever ever use eval or goto calls – if you find yourself considering these in your code then step away from your computer, go into a quiet darkened room and think carefully about your life choices. Programming is not for you.
It actually amazes me that PHP still supports these calls, but I do have respect for whatever genius wrote the PHP man page for goto.

23
Apr '14

by john

PHP’s callback functions are known as being ‘dark magic’ but there are two array functions, namely array_map and array_filter which can be incredibly useful (and not that scary).

array_map gives you a very simple way of calling a function on each element of an array and returning the result in another array. I make great use of it when working with ORM models as it is perfect for extracting an array of IDs, names, email addresses or whatever from a model array.
As an example let’s imagine I have an array of User objects which have ‘name’ fields that I want to extract. I can simply do the following:

$names = array_map(function($user) { return $user->name; }, $users);

Ain’t that simple?

array_filter works in a very similar way but is used to run some logic against each element in an array, in order to decide whether that element is returned as part of the output array.
So if my User objects also had an ‘age’ field and I wanted to extract all users who are 18 years old or more I could do this:

$adults = array_filter($users, function($user) { return ($user->age >= 18); });

Now any readers paying attention will notice that in the above functions the parameters are swapped round i.e. array_map has the callback first and the array second and array_filter is vice-versa. It looks unpleasant but there is a degree of logic to this as array_map will accept multiple arrays as arguments, and array_filter doesn’t require the callback to be provided at all (in that situation all elements that evaluate as false would be removed).
Having said that PHP is famous for its inconsistent ordering of parameters in its core functions and it remains my biggest gripe with the language, just very slightly in front of most of its methods being in the root namespace. But hey, you can’t have everything right?

20
Mar '14

by john

Anyone who has tried to build a RESTful web service in Laravel will know all about resource routes. With a single route statement you can respond to all of your verbs (actions) for a given resource:

Route::resource('users', 'UserController');

Then create your UserController class with any/all of the following functions, as required:

GET /resource
public function index() {}

GET /resource/create
public function create() {}

POST /resource
public function store() {}

GET /resource/id
public function show($id) {}

GET /resource/id/edit
public function edit($id) {}

PUT /resource/id
public function update($id) {}

DELETE /resource/id
public function destroy($id) {}

Great! Works really well for basic CRUD, no worries there. However what if you want to run these actions for a resource that sits below another? e.g. Your users sit below separate clients and need to be managed independently. Well, despite no reference to this in the Laravel documentation, it turns out this is very easy indeed:

Route::resource('clients.users', 'UserController');

Then simply add your client ID to the URLs and function arguments as so:

GET /client/client_id/resource
public function index($client_id) {}

GET /client/client_id/resource/create
public function create($client_id) {}

POST /client/client_id/resource
public function store($client_id) {}

GET /client/client_id/resource/id
public function show($client_id, $id) {}

GET /client/client_id/resource/id/edit
public function edit($client_id, $id) {}

PUT /client/client_id/resource/id
public function update($client_id, $id) {}

DELETE /client/client_id/resource/id
public function destroy($client_id, $id) {}

And you’re done! Boom!

22
Oct '13

by john

After a long break from doing anything with Ruby (On Rails or otherwise) I’ve had cause to get my head back into Capistrano lately and am really enjoying it, however it’s fair to say that documentation, particularly for deploying anything other than Ruby apps, is rather lacking.
The biggest difficulty I has was in making the script exit cleanly if a branch / tag was specified that doesn’t exist. The update logic was so wrapped up in the core of Capistrano that I had a devil of a time tracking it down. So, for all who have a similar problem, here is the solution I found:

desc 'Update the code and fail cleanly if branch not found'
task :update do
 transaction do
  begin
   update_code
  rescue
   puts "Branch / Tag not found"
   exit
  end
 end

 create_symlink
end

What I am doing is simply overriding the core ‘deploy:update’ task and recreating it with a begin-rescue around the ‘update_code’ call. Happy days.

28
Aug '13

by john

You won’t often find me posting an IE only chunk of code here but today I’m making an exception as I have found myself writing a site specifically for use in a call-centre where I know for a fact that everyone will be using IE so I can make a few custom nice-to-haves with that in mind.

IE, for all its faults, is the only browser that will let you implement a copy to clipboard function without the need for Flash plugins. There are lots of tutorials out there that show you ways to do this, but I ended up building a very quick jQuery function that I thought I’d share.

This assumes that you have a container with a class of ‘copy_text’ and a button, link or other clickable element with the class of ‘copy_to_clipboard’:

$('.copy_to_clipboard').click(function(e) {
    e.preventDefault();

    if (!document.all)
        return; // IE only

    var copy_text = $(this).siblings('.copy_text').html();
    var new_element = document.createElement('input');
    new_element.setAttribute('type', 'text');
    new_element.setAttribute('class', 'copy_text_dynamic');
    new_element.setAttribute('value', copy_text);
    document.body.insertBefore(new_element)

    r = new_element.createTextRange();
    r.execCommand('copy');
});

Now you’ll notice this has created an input element on the fly. This is because IE’s createTextRange call only works on input elements so we have to create one and fill it with the text that we want to copy to the clipboard.

The final part of this process is making sure that this newly created input element doesn’t show up on our page. You may have already noticed that you can’t hide an element (i.e. display: none) in IE if you want to do anything with it as it doesn’t bother putting hidden elements in the DOM. That being the case, as an alternative I prefer to fix the position of the element and send it way off the side of the screen like so:

.copy_text_dynamic {
    display: block;
    position: fixed;
    left: -10000px;
}