Archive for the ‘Programming’ Category

PHPUnit and PEAR packages break on Mountain Lion

Monday, August 6th, 2012 | Programming, Tech

If you have recently upgraded to Mac OS X Mountain Lion (10.8) you may find that PHPUnit and other PEAR packages no longer work. You may get errors similar to the following.

PHP Copy & Paste Detector

Warning: require(PHPCPD/Autoload.php): failed to open stream: No such file or directory in /Users/chris/pear/bin/phpcpd on line 49

Fatal error: require(): Failed opening required 'PHPCPD/Autoload.php' (include_path='.:') in /Users/chris/pear/bin/phpcpd on line 49

PHP Mess Detector

Warning: require_once(PHP/PMD/TextUI/Command.php): failed to open stream: No such file or directory in /Users/chris/pear/bin/phpmd on line 38

Fatal error: require_once(): Failed opening required 'PHP/PMD/TextUI/Command.php' (include_path='.:') in /Users/chris/pear/bin/phpmd on line 38

Unfortunately, there doesn’t seem to be an easy way to fix them, other then by reinstalling each package.

sudo pear install --force --alldeps phpunit/phpunit
sudo pear install --force --alldeps phpmd/PHP_PMD

The tools should then run as expected.

LESS & SASS

Thursday, July 19th, 2012 | Limited, Programming, Tech

Still writing regular CSS? Pfft, you’re living in the dark ages! These days it’s all about two new technologies that are almost identical, so I’m going to discuss them in the same post.

The idea is dynamic stylesheets – bringing concepts we use every day in regular programming and implementing them in stylesheets to avoid duplication and make everything cleaner, nicer and more up to update with current paradigms.

So what can you do with these tools? Here is a quick overview…

Variables

Using a colour everywhere that you might want to change later? No worries, just save it as a variable and if you do need to change it at a later date, you just update the variable and it will be changed everywhere.

@myColour: #FFCC00;

.header { background: @myColour; }
.footer { background: @myColour; }

Mixins

Inheritance! What a sexy thing to have in CSS. No longer do you have to place loads of DOM references in lots of different places. Now you can just write it once and included it wherever else you need it.

.bigBorder { border: #FF99CC 10px solid; padding: 5px; }
.header { .bigBorder; background: @myColour; }
.footer { .bigBorder; background: @myColour; }

Nested rules

This one is a huge time saver! How many times have you had to reference half a dozen elements in one DOM reference? Probably very rarely, but certainly two or three tags is the every day reality. No longer though, because you can now nest your rules.

.header {
	.bigBorder
	
	a {
		font-size: 200%;
	}

In this example, the 200% font size will only apply to a tags inside .header, just as if you had done .header a in your DOM reference.

Operations

Want to make a header colour slightly darker? No worries, just add two colours together.

@mainColour: #FFCC00;

.header { background: @mainColour + #333333; }

But these are just a few of the features of these languages. They allow you to do a lot more – including things like full blown functions that you can pass parameters into, guards and much more.

The main difference between LESS and SASS is that LESS is a client-side JavaScript library (although has now been ported to Node) – you send the browser your .less file and include a JavaScript library that converts it. Meanwhile, SASS is a Ruby Gem that compiles a stylesheet to send to the client each time you edit your .sass file.

To find out more, visit the LESS and SASS websites.

Lithium

Tuesday, July 17th, 2012 | Programming

Recently, I’ve been re-developing Authority Forums and as part of the re-development, the site has been re-built from the ground up, using the Lithium framework.

Lithium, which bills itself as “the most RAD framework for PHP” is a spin-off from CakePHP. I’ve used the CakePHP framework for previous projects, and it’s an OK framework, but I didn’t find it to be something special. Neither did some of the core developers apparently, who left to start Lithium. It’s also contributed to by Richard McIntyre, who gave the talk on The Future of PHP that I blogged about last month.

It is an easy framework to get started with. I say that; it took me twenty minutes to work out that I needed to download both the Lithium and framework packages to get started. But once I had stopped missing the obvious, everything was up and running very smoothly.

In particular, creating models was very easy. All you do is create a class with the name of your database table and have it extend the Lithium base model. That’s it! You don’t have to tell Lithium what the content of the table is, it figures all of that out by itself and gets you up and running with a CRUD-supporting model immediately.

Of course, this isn’t always ideal for performance and security reasons, but you have significant customisation options that you can dig into to tweak things as you need them. Or, if Lithium just isn’t doing the trick to you, you can easily replace it with Doctrine, or any other ORM of your choice.

It also comes with a good range of built-in libraries. Perhaps not quite as comprehensive as Symfony2, but certainly easy to get started to and that just turn on and off as you wish – most are off by default but can be turned on my uncommenting a few lines. It also has ground-up support for MongoDB.

Deploying was easy too. Lithium automatically figures out whether the current install is dev, test or production and adjusts everything appropriately, so all you do is enter the connection details for databases on each environment and Lithium intelligently figures out which ones to use without you having to tell it, removing the need for slightly different code or a non-writable configuration file.

That said, deployment wasn’t quite as smooth as it could have been, and resulted in a bit of last minute panic. Lithium’s major weakness right now is the lack of community support and documentation. The documentation they provide is fairly good, but unless you’re doing exactly what the example is showing you will run into problems.

I would say I spent more time digging around the API documentation than I did the manual. This isn’t the case with Symfony2 (though I’m not a fan of the Symfony2 documentation either), so if you’re not comfortable doing this, it’s a tough framework to work with. More importantly, though, there just doesn’t seem to be other users doing real-world stuff, and so on several occasions, I had to find myself guessing at how to use functionality.

A good example of this is how to filter a query based on a range. It is easy to do a “I need this column to equal this” for example, but what happens when you want to do “I need this column to be greater than this.” In the end I guessed you could supply a sub-array with the value and the operator – and it turns out you can! But I couldn’t find any documentation for this, even though the functionality clearly is there. What they really need is a user forum (and users! It could just be on Stack Overflow like every other piece of knowledge you ever need).

Overall, I’m really enjoying using the Lithium framework. Its lack of user community is a massive drawback, but wider adoption will solve that and it should be more widely adopted because it’s a great framework.

Wing Commander

Thursday, July 5th, 2012 | Limited, Programming

Moustache I’m a big fan of the Flight PHP micro framework, and it’s built-in views component is quite nice when you want to do stuff in a rush.

But recently I have started to use Slim more often as it has almost out of the box support for Mustache templates, whereas Flight does not.

Until now, that is. I wanted to use Mustache with an existing project I had already coded up in Flight, so I’ve now written a wrapper for it and released it on Github. It’s nothing fancy – probably less than 100 lines of code in total. But it seems to get the job done.

So if you’re looking to use Mustache templates in your Flight application, why not give it a go? If you have any improvements, you can always fork it too!

Logic-less templates with Mustache

Wednesday, July 4th, 2012 | Limited, Programming

The first thing you probably think about when I mention Mustache is, “you’ve spelt moustache wrong.”

You would be right. But although the creators of such a project clearly do struggle with proper spelling even more than I do, they have never the less created something really interesting – logic-less templates.

Mustache is a templating system, similar to Smarty or Twig, that was originally written for Ruby and has since been ported to almost every other popular language under the sun (it has not been ported to any languages that exist outside our solar system, to my best knowledge).

The idea is that you separate out your logic from your template. So you would have a view class which handles the logic, and then the actual template file which has your presentation in. Why this extra layer of complexity though?

Well the problem with templating systems such as Twig is that they actually aren’t as separate as we like to think they are. You have control statements like looks and if statements, and then people started adding helpers to templating systems where you could call functions and even pass parameters! This made it a lot easier for us to write the view, but by the time you’ve added all that in, why not just place the PHP directly inside the template – it would be just as simple.

Mustache does a way with all that. In Mustache there are two main types of tags you can have – variables and sections. A variable is a straight replacement in double brackets {{like this}}. Sections contain one extra character so you might have a {{#section}} that wraps this text{{/section}}. A section can then be repeated zero or more times depending on whether you pass it a false value, a true value or an array.

There are a few other tags but this for the most part is everything! You don’t have the complicated control statements, the helper functions or other such syntax to deal with – inside a section which repeats from an array for example, you just call the key name, without having to specify the array variable every time. See the example below.

In Twig, you would do this...

{% for item in list %}
{{item.name}}
{% endfor %}

In Mustache, you just do this...

{{#list}}
{{name}}
{{/list}}

You can argue that there is added complexity in having to create an accompanying view class – and you would be right. But this is optional, and only required if you need to do view-time processing – passing an associative array, just like you would with Twig, works fine too!

I highly recommend giving Mustache a go, I was skeptical at first but once you dive in it really produces some beautifully clean code.

Slim

Tuesday, July 3rd, 2012 | Limited, Programming

Slim is a PHP micro framework, similar to Flight, Silex and Limonade, not to be confused by the Ruby templating system of the same name. It claims to contain “everything you need and nothing you don’t.”

If functions like you would expect a micro framework to work. Here is the standard example.

<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name!";
});
$app->run();
?>

My favourite part of Slim, however, is actually the Slim Extras bundle which doesn’t ship with it, but can easily be downloaded and dropped in. This adds easy integration for lots of different templating languages – notably Smarty, Twig and Mustache.

So, for example, if you wanted to integrate Twig, just grab the Extras bundle, the Twig bundle, include the relevant file and change your initialisation statement to the following.

$app = new Slim(array("view" => "TwigView"));

That’s all – now you’re away and can call the render method with a filename and data array to render a template using Twig.

Mustache

Wednesday, June 27th, 2012 | Limited, Programming

Mustache is a logic-less templating system, written by people who apparently can’t spell moustache correctly.

It has been ported to almost every popular language ranging from PHP to C++, though it has its origins in Ruby. It isn’t just useful for HTML either – you can also use it for things like config files.

The idea behind it is that templates are logic-less. It divided the traditional view into two parts – a view which is a class in your host language, and a template which is the Mustache markup. The view class can also be an associative array, like you would pass with a traditional templating system, but using a class allows you to easily make use of functions.

It produces very clean mark-up – you simply place your variables in curly braces (or double moustaches if you will) like {{so}} and they are swapped out. Repeating sections are handled by {{#sections}} that repeat based on lists {{/sections}} or are just used once to display or not, instead of using if statements.

The advantage is that you get templates which are almost logic free. I saw almost because of course you do still have repeating elements and tags in there designed to replicate if statements. But there are no logical statements in there – just tags!

The disadvantage is that it means doing a bit more work with your views. MVC already splits out the stack into three components and Mustache divides the view one step further.

Motivating unit testing with a reduction in functional testing

Thursday, June 21st, 2012 | Programming

The problem with unit testing is that developers don’t want to write them. No surprise, there, they aren’t the most exciting thing in the world, unless you’re actually a tester and they are your pride and joy.

So, the challenge for creating a good development and testing cycle is how to ensure your developers are motivated to actually write the unit tests. Test driven development is a good way to go about this, and helps stop developers over-engineering too, but it requires a radical shift in your workflow.

Perhaps a less extreme modification, and one developers are more likely to buy into is to replace functional testing with unit testing.

Back in the old days, when you were working on a web application for example, you would write some code, you would then load it up in your browser and see if it worked. If it did you would move onto the next thing and if it didn’t you would go back and fix it.

Then the rise of unit testing for web applications came along and developers were asked to write the code, functionality test it and then write a unit test for it. But none of them did because they didn’t want to write a boring unit test.

However, recently I was writing a model for a web application. Having made my changes, I then wrote a new test for it in our set of unit tests to ensure that it worked as it should. I ran the tests, and I did. But, being pressed for time, I never actually ran a functional test on it. But it worked. Which is no huge surprise, given it passed the unit test.

But what if that was policy? All you had to do was to write the unit test and for it to pass that, you didn’t have to do a functional test. Developers might buy into that, because it takes roughly the same time (probably a little more, but not too much to worry about) and you don’t lose too much. Here is why:

You can’t get away from functional testing. At some point, someone is going to have to do a functional test and at that point they will see if it works or not, and knock anything that doesn’t work back to the developers. This isn’t the case for unit tests – you can go without them, it just means you end up producing pretty rubbish unreliable code and end up spending ages tracing issues down later. But it isn’t an in your face blocker, so developers often ignore it.

Of course, I wouldn’t recommend this for organisations who already have a testing culture embedded. But for organisations that don’t currently unit test, relaxing your rules on functional testing could help you take that first step down the road.

Using the Symfony2 Validator component outside the framework

Wednesday, June 20th, 2012 | Limited, Programming

Symfony2 has a very nice Validator component for data validation. As with most of the components, it can be used outside of the framework, but unfortunately, the documentation on how to do this is rather lacking. Indeed, even using it within Symfony but outside the controller can be difficult and this is made especially difficult if you’re using Propel because you can’t use annotations.

However, it can be done, and this tutorial will show you how.

When using the validation component somewhere other than in a Symfony2 controller (be that in an entirely different project, or just in a custom class inside the framework), the problem is that you don’t have access to the service container. So we need to create the object for ourselves.

Lets start by importing the namespace into our class.

use Symfony\Component\Validator as Validator;

This will give us quick and easy access to the Validator classes. Now we can use the ValidatorFactory to generate a validation object.

$factory = Validator\ValidatorFactory::buildDefault();
$validator = $factory->getValidator();

This is good. It means we now have a validation object that we can run against annotated classes. But what if we are using Propel and need to specify our validation rules in a YAML file?

$yamlFile = "../src/Acme/DemoBundle/Resources/config/validation.yml";
$factory = Validator\ValidatorFactory::buildDefault(array($yamlFile), false);
$validator = $factory->getValidator();

Now we can use the rules we specified in the YAML file to validate our Propel classes.

$violations = $validator->validate($model);

Splendid, we’re done. One further trick I’ll throw in with this post – what happens when you need to validate multiple objects and give a combined list of errors back? Because the list we get back is a custom object, we can’t just array_merge the two $violations list. But luckily, there is a function in the object to do this.

$violations = new Validator\ConstraintViolationList;
$firstViolations = $validator->validate($firstModel);
$secondViolations = $validator->validate($secondModel);

if ( count($firstViolations) > 0 ) {
	$violations->addAll($frstViolations);
}

if ( count($secondViolations) > 0 ) {
	$violations->addAll($secondViolations);
}

That will return you a single ConstraintViolationList that you can iterate through, containing errors from both models.

Limonade

Tuesday, June 19th, 2012 | Limited, Programming

I’ve recently written about Flight and Silex, so continuing the PHP micro framework theme, this post is looking at Limonade.

I had heard mixed reviews about it before I first began exploring the framework, and that pretty much sums up how I feel about it too. It does what it needs to, but there is nothing spectacular about it and given the choice, I would rather work with something like Flight.

It offers similar functionality, with an integrated views system, though without the object orientation you would expect, which makes it more similar to Sinatra. It also has a good range of hooks to allow you to extend functions by inserting code before and after.

Documentation for Limonade is a little hit and miss. There is quite a lot of it but it isn’t very well organised. If something isn’t in the main readme, you often have to go hunting around the examples folder until you find what you want. In its defence though, there is a lot of ground covered in the readme.

You can download it and have a play around from the Limonade website.