Learn More About PHP And The Web Platform!

Struggling with your web server, or to scale your PHP application to meet growing demand?

Whether you're running one server or a whole server farm; whether you're hosting on Windows Server or on Linux.

Learn from Stuart's experience with system design, delivery, support and management to help you do a better job and have an easier time.

Beneath Whitby breakwater

I’ve recently switched from using Netbeans as my PHP dev tool of choice to Sublime Text 2. Features-wise, I think Netbeans is great. During the years I used it, I never felt that there was a feature I needed that was missing at the time. But, like all the current crop of Java-based desktop IDEs, it’s so damn ugly [1] and slow [2] that I’ve had enough. I program because it’s something that I love doing, and anything that gets in the way of that … I’ve no time for any more. So when a work colleague introduced me to Sublime Text 2, I was in the mood to give it a go, and 3 months on, I haven’t opened Netbeans once.

I’ll be the first to say that Sublime Text 2 isn’t for everyone.

  • It’s a beta product, which means there are some rough edges (mostly in the plugin API I feel), but it’s more than stable enough for production use. It has crashed a couple of times, which might put some people off, but I don’t recall losing any work as a result. File management in the project pane still needs work. The regular dev builds occasionally break things.
  • It isn’t a full-blown IDE; it’s more like the spiritual successor to TextMate, an editor that I never personally cared for. In particular, it doesn’t support interactive debuggers, which means no Xdebug support, and there’s currently no obvious way for a plugin to add that functionality in [3].
  • Auto-completion isn’t anything like what you’re used to. The built-in auto-completion is based on a mix of static knowledge of languages and fuzzy matching against what you’ve recently typed. There’s no obvious intelligence about the code you’re working on, nor the parameters for any method or function. These are two things that many people will deeply miss. [4]
  • It isn’t free, but you can evaluate it for free with no time limit. If you decide to buy, it’s substantially cheaper than both PhpStorm and Zend Studio, and there’s no annual subscription element to the licensing. You’re buying a license to support and encourage an independent developer, and to show your appreciation for a very nice piece of software.
  • It’s a closed-source product. You can’t fix it yourself if it breaks, and no-one can pick up the reigns if it gets abandoned. There seems to be just one guy behind it, and if anything happened to him, that’d probably be the end of the product. That said, most of the alternatives are also closed-source too.

Given all of that, why have I switched?

  1. Sublime Text 2 is very very fast. Sublime Text 2 itself opens instantly. Files open instantly (provided they’re not 100 megabyte test data files). In fact, everything happens instantly – even inside a virtual machine running on a 3 year old laptop. There are no pauses for anything to be indexed, and I’ve never seen CPU usage spike – important for us untethered users and our suffering laptop batteries [5]. And if a plugin slows things down at all, Sublime Text 2 tells you which one is the culprit so that you can go and disable it. I’d compare the importance of the speed difference to switching from a hard disk to an SSD. You don’t realise how much you’re waiting for your slow Java-based IDE until you use something that’s properly fast.
  2. It renders fonts properly – Droid Sans Mono and Ubuntu Mono in particular both look gorgeous – and even after a long day of use, my eyes don’t feel like they’ve been scratched on the inside by sharpened kitty claws all day long [6]. True story: one of my colleagues came over to ask what I was using, because he thought it looked so nice from a distance. When was the last time anyone ever thought that about a desktop Java app?
  3. All of the searching is based on an extremely powerful fuzzy matching approach. Netbeans supports regexes, which can be very handy, but most of the time when I’m looking for something, a regex is overkill but a simple string search isn’t powerful enough. If I’ve got both a class called ‘IpcProcess’ and ‘IpcProcessID’, in Sublime Text 2 I can find the ‘IpcProcessID’ class by searching for ‘ipi’; I just have to type the shortest set of characters that uniquely matches what I’m looking for. It’s much quicker than writing (or running) a regex, and soon becomes second nature.
  4. There’s a “goto anything” search panel which is lightning quick. Combined with the fuzzy matching approach, I find this a godsend for working on multiple large code bases, where there may be different classes with the same base filename, or duplicate installs of a class in vendor folders, or where I’ve got both trunk and branches checked out for the same project. It’s a killer feature, and one that has changed my workflow for the better, especially combined with my next reason. The panel’s also like using Google Instant – you get results as you type, giving you the instant feedback you need to refine your fuzzy search. (There is also a “goto symbol” search panel, and a “command palette” which allows you to search through the available editor commands to execute).
  5. Everything can be done from the keyboard. Everything can be done from the mouse too, but I found that doing everything from the keyboard is both faster and doesn’t break the flow of what I’m working on. This is something I didn’t appreciate until after I’d switched, but it’s a fantastic help to me when I’ve got another developer sat next to me and we’re looking at (or for) something together. Together with the fuzzy matching, it’s like doing software archaeology with a JCB digger instead of a trowel.
  6. It does a great job of auto-detecting whether a file uses spaces or tabs for indentation, and how big the tab stop is. There are days when it seems like no two files I open are consistent in how the code is indented, and it’s rare for anyone to have tagged on a modeline to give any hints. With Netbeans, which has a rigid config-based approach to indentation, I end up playing code-formatting table tennis with the original author of the file, as we always seem to have different indentation settings. Sublime Text 2 works out what the existing indentation approach is, and just auto-configures itself to match. It’s a great time saver [7].
  7. It strips trailing spaces from the ends of lines when I save my files. This has been broken in Netbeans for years! It’s a small thing, I know, but it really annoys the crap out of me that Netbeans doesn’t get this right. As a bonus, in Sublime Text 2 trailing spaces actually get their own setting in color schemes, so you can see exactly where they are. In Netbeans, they’re bloody invisible 🙁
  8. There’s a healthy ecosystem of plugins for it – over 200 plugins and counting – thanks to Will Bond’s Package Control package manager. Will is doing a great job of making sure that each plugin is tightly focused on sorting one problem only, to keep Sublime Text 2 as flexible and adaptable as possible – something to keep in mind if you start writing plugins yourself.
  9. Creating new plugins is very easy. It took me just one evening to add and release the initial PHPUnit plugin, and that included the time it took to learn both Python and the plugin API from scratch. To make an update to your plugin, simply push your changes to your master branch on GitHub. It’s as close to frictionless as you can get.
  10. I can own the tool, and set it up to suit my approach to programming. Because extending the editor is so effortless, I can automate anything that I want, to suit exactly how I want it done. I can create snippets, intelligent macros, and full-blown plugins to suit, and I can make them as and when some new need occurs – even one-off tasks. In this, it reminds me most of JED, which was my text editor of choice back in the 90’s for exactly the same reason. It’s the same reason folks love Vim. (Btw, Sublime Text 2 has a Vim mode. I haven’t tried it, so I can’t vouch for whether it’s good enough to tempt Vim users over or not).

Like Netbeans, Sublime Text 2 works on OS X, Linux and Windows [8], so I can use it everywhere I used to use Netbeans. I reckon it occupies a sweet spot that makes it very well suited to scripting languages and C/C++ development, albeit minus support for interactive debuggers.

At work, some of us have taken to it, and some of us haven’t. I’m happy to recommend it to anyone who’s looking for a change. You can take advantage of the open-ended free evaluation period, and see if it suits you or not. It’s working for me so far, and I probably spend more time using it than any other app on any of my computers.

If you do like Sublime Text 2, I’d love for you to leave a comment below with your own reasons why.

Footnotes

  1. Dear Java, the 1990’s called and asked for their crappy non-aliased font renderer back. I think Windows 3.11 is missing it terribly.
  2. There was a similar parallel around 20 years. At the time, Emacs was by far the most fully-featured editor, but everyone I know chose vi because of how slow and bloaty Emacs was at the time. It was so bad, we used to say that Emacs stood for “Eight megs and constantly swapping” (this was back in the days of 640K of RAM).
  3. The lack of debugger support is, for me, the one feature that I miss every single day.
  4. There is a plugin that tries to bring Komodo’s auto-completion to Sublime Text 2, but it stopped working for me before Christmas sadly.
  5. It’s like when you switch from Firefox to Chrome for the first time … your laptop just gives a sigh of relief, and you don’t have to worry quite so much about how far away you are from the next convenient wall socket to recharge from. I can easily imagine running this on a netbook, or a laptop with very aggressive CPU throttling in place – both places where a Java-based IDE would struggle.
  6. I’m highly visual, and find it really tiring to spend 10-12 hours a day in front of poorly-rendered fonts.
  7. Now, if only everyone just did the right thing in the first place and used spaces instead of tab characters, we wouldn’t need functionality like this … 🙂
  8. The keybindings are different from one platform to another, and because Python isn’t a platform-agnostic language, some plugins may not work properly on Windows at first. But most plugin authors are happy to accept pull requests with portability fixes.
99 comments »

PHPUnit Plugin For Sublime Text 2

Posted by Stuart Herbert on February 4th, 2012 in Toolbox.

Sublime Text 2 is a new cross-platform text editor that I’ve recently switched to. It’s still in public beta, but already offers better performance (and battery life!) and a better look (fonts that render properly!) than Java-based IDEs such as Netbeans.

One thing it didn’t have was support for PHPUnit, so I’ve made a plugin. It’s available to install via Package Control.

You Need A phpunit.xml or phpunit.xml.dist File

To use this plugin, your project needs to contain either a phpunit.xml or a phpunit.xml.dist file. This file contains all the configuration that needs to be passed to PHPUnit. The plugin searches upwards from your code, and will favour a phpunit.xml file over a phpunit.xml.dist file if it finds both.

If you don’t have one, you need to go and create one now.

How To Use

If you have your code open in a Sublime Text 2 window, right-click inside the window to see what your options are:

  • Test This Class – click this option to run just the unit tests for this class.

    This option appears if the PHPUnit plugin can find your unit tests. It takes the name of your class, and uses the standard PSR-0 transformation to figure out what the name of your test file should be.

    For example, if your class is called ‘Phix_ProjectCommandLineLibCommandParser.php’, the PHPUnit plugin will search for a file ‘CommandLineParserTest.php’ that’s in a folder called ‘Phix_Project/CommandLineLib’.

  • Open Test Class – click this option to open up your tests in Sublime Text 2. If you already have the tests open, this will switch tabs to your tests.

    Again, this option only appears if the PHPUnit plugin can find your unit tests.

  • Run All Unit Tests – click this option to run all the unit tests for your code.

    This option just points PHPUnit at your phpunit.xml or phpunit.xml.dist file.

If you have your tests open in a Sublime Text 2 window, right-click inside the window to see what your options are:

  • Run These Tests – run these unit tests, using the phpunit.xml or phpunit.xml.dist file that the PHPUnit plugin has found.
  • Open Class Being Tested – open the class that these tests are for in Sublime Text 2. If you already have the class open, this will switch tags to your code.
  • Run All Unit Tests – click this option to run all the unit tests for your code.

If you’re someone who prefers keyboard over mouse, then you’ll probably want to run the PHPUnit plugin commands from Sublime Text 2’s Command Palette:

You get the same commands that appear on the right-click menu … the right commands will appear for the file that you’re currently editing, just as you’d expect.

Finally, you can also right-click on your phpunit.xml (or phpunit.xml.dist) file in the Project Sidebar, and run your unit tests using that specific config file.

Helpful Snippets

Like TextMate before it, Sublime Text 2 also has a handy snippets feature, where it can insert a pre-crafted block of text (or, in our case, PHP code) to speed up your coding. I’m collecting most PHP-related snippets in my Additional PHP Snippets plugin (hat-tip to Rob Allen for the inspiration for this), but the PHPUnit plugin includes a few PHPUnit-related snippets to help.

  • phpunit-testcase – will create a new test class for you to fill out.

    I find this handy mostly so that I don’t have to remember which class my test class has to extend 🙂

  • phpunit-test – will create a new test method for you to fill out.

To use any snippet, type its name and then press the <TAB> key. Sublime Text 2 will insert the snippet, and then you can use the <TAB> key to cycle through any placeholders that you need to edit.

If you find snippets useful, please don’t forget to check out my Additional PHP Snippets plugin too!

Feedback, Contributions Welcome

I’d love to hear how you get on with the plugin, and any ideas you might have for additional features. And pull requests via GitHub are most welcome too!

Be the first to leave a comment »

Phix 0.15 Released

Posted by Stuart Herbert on January 31st, 2012 in phix.

Phix v0.15 is now available from pear.phix-project.org.

This release is dedicated to my Dad, Leslie Herbert, who passed away in December 2011 whilst I was recovering from surgery. He was always encouraging me to spend as much time as possible working on my own software, and I’m sure he’d be happy that his PC has become my new dev box for working on things like Phix.

What’s New In This Release

  • phploc support – the “phing code-review” command now also calculates the size of your component using phploc.
  • subset support – you can now do “phix php-library:init –subset=<role>[,<role> …]” to create components that only contain some of the different file types supported by the PEAR Installer. There’s also a “phix php-library:removeunusedroles” command if you want to strip unused roles from an existing component.
  • phpunit.xml.dist support – components now use phpunit.xml.dist by default, so that you can put your own phpunit.xml in place if you ever need to override the default settings.
  • src/README.md – we now drop a (hopefully helpful) README file inside the src/ folder to explain what goes where.
  • misc robustness improvements to build.xml files – I’ve made some small tweaks to the build.xml file to try and catch a few error conditions and display helpful messages.
  • internal debugging – “phix -d …” (which has been documented for several release now) enables internal debugging tests inside Phix and its components. It’s mostly there for me to use, but I thought I’d mention it in case you’re testing a patch for phix before sending it to me.

A big thanks to everyone who attended my workshop at PHPNW11 in October for their feedback and feature requests for this release.

How To Install

To install Phix, we have handy one-line install scripts on the Phix project homepage. And I’ve put together a screencast of how to install Phix on Ubuntu. It’s my first ever screencast, so please be gentle 🙂

How To Upgrade

To upgrade from an earlier release of Phix, please do the following:

sudo pear clear-cache
sudo pear upgrade phix/phix4componentdev

Once you’ve upgraded phix itself, don’t forget to go into each of your components, and run

phix php-library:upgrade .

to upgrade all of the skeleton files (build.xml et al) for your component.

What’s Coming In Phix 0.16

Windows support hasn’t happened yet, but I hopefully have a volunteer who is going to look into that during February.

My priority for phix-0.16 is to make it easy to build phix-based components in Jenkins, based on Sebastian’s Jenkins Template. I’m doing this next because I’m not sure how much I’ve got to change things to suit Jenkins, so I’d rather get it done sooner so it’s done and out of the way. (And I promise that I haven’t forgotten docblox support either …)

Our roadmap has all the details.

Be the first to leave a comment »

One of the questions I’ve been asked after yesterday’s blog post about Phix’s ContractLib is why not just use PHP’s built-in assert() function? I think it’s a great question, and the best way to answer it is to take a look at the key differences between two solutions.

Side By Side Comparison

Feature assert() ContractLib
Implementation PHP extension written in C (ships as standard part of PHP) PHP library written in PHP
Enable / disable execution Partial (there is an overhead when disabled, but it’s low) Partial (there is an overhead when disabled, but it’s higher)
Issues PHP4-style warning when tests fail Yes (configurable) No (throws a ContractFailedException instead)
Terminate PHP script when tests fail Yes (configurable) Only if the ContractFailedException is never caught
Quiet eval of test expression Yes (configurable) No (not required; test expressions are pure PHP code, not eval() strings)
Callback on failed test Yes (configurable) No (unwinds the stack instead by throwing ContractFailedException)
Throws Exception when tests fail No (but can emulate if you write your own assert() callback method) Yes (standard behaviour)
Tests are pure PHP code No – recommended way is to pass strings into assert() to be eval()’d Yes
Error report includes original value that failed the test No Yes
Support for per-test custom failure messages No Yes – are required to provide one
Support for Old Value storage and recall No (but can emulate by hand) Yes

The Differences Explained

The key difference is one of philosophy. assert() sits well with the PHP4 style of error reporting and handling, whereas ContractLib is firmly in favour of the OO world’s approach to reporting errors.

It’s a personal preference, but I think that PHP4-style errors have no place in code that has any desire to be robust. Exceptions aren’t perfect, don’t get me wrong, but their core property of unwinding the call stack in an orderly fashion makes writing robust code much easier. And they also carry a payload – information about what went wrong and why – which PHP’s assert() cannot provide to the same extent.

It’s much quicker to debug something when there’s a record of the value that failed the test. For that reason alone, I’d always prefer something like ContractLib over the built-in assert() approach.

But we can’t ignore the fact that these are tests that get shipped to, and executed in, the production environment. Unlike unit tests, adopting programming by contract will slow down your PHP code in production. The question is: by how much?

What About The Performance?

I’ve done some benchmarking between the two, using the five tests listed in the final example in yesterday’s blog post. It’s a real-world example of the kind of tests that I would look to add to code to improve robustness.

Here are the results I gathered, calling the tests 10,000 times in a tight loop. The tests were run from the command line, and the times do include PHP start-up / shutdown time and the time taken to parse each test file. I assumed a best-case scenario, where the tests would always pass.

Test Approach Time w/ Tests Disabled Time w/ Tests Enabled
Tests written using assert() 1.103s (100%) 5.989s (543%)
Tests written using ContractLib 3.055s (277%) 3.096s (281%)

When tests are disabled, using assert() is much cheaper than using ContractLib today. That’s to be expected, as assert() is written in C. I imagine that we could get close to the same performance if ContractLib was rewritten in C as a PHP extension.

But, when tests are enabled, assert() is much slower than ContractLib. Why? Because the recommended way to use assert() is to pass the test in as a string. PHP has to convert that string into bytecode to execute, and that conversion appears to be quite expensive.

Given the choice, I’d rather trade things running a little slower in production for having much faster tests when I’m writing code, and that’s why I created ContractLib. Plus I get much better information to understand why the test failed, and if I wanted to run the tests in production, I can handle their failures in a much saner way.

Final Words

In my experience, the time it takes to develop and ship code is normally more critical than how fast the code runs in production. Developer time has become a scarcer resource than CPU time.

Used intelligently, these kinds of tests in your code can help your team deliver quicker, because the code they are using and reusing is more robust first time around. Programming by contract is different to, and complements, unit testing because contract tests catch errors in using the code.

Whether you use ContractLib, assert(), or you create your own solution, you should really consider how much it is costing you when you don’t use these kinds of tests.

Be the first to leave a comment »

In my last blog post, I introduced ContractLib, a simple programming by contract library that I’ve created for PHP 5.3 onwards. And I promised some examples 🙂

Installing ContractLib

ContractLib is available from the Phix project’s PEAR channel. Installing it is as easy as:

[code lang=”bash”]
$ pear channel-discover pear.phix-project.org
$ pear install -a phix/ContractLib
[/code]

At the time of writing, this will install ContractLib-2.1.0. We use semantic versioning, so these examples will continue to work with all future releases of ContractLib-2.x.

Adding ContractLib To Your Project

Assuming you’re using a PSR-0 compatible autoloader, just import the Contract class into your PHP file:

[sourcecode language=”php”]
use Phix_ProjectContractLibContract;
[/sourcecode]

Adding A Pre-condition Contract To Your Method Or Function

Take a trivial method like this:

[code lang=”php”]
class ActionToApply
{
public function appendNow($params)
{
$params[] = time();
}
}
[/code]

This method works fine … until someone passes a non-array as the parameter. At that point, your code stops working – not because your code is wrong, but because someone used it in the wrong way. This is a classic cause of buggy PHP apps. Thankfully, it’s very easy to address using ContractLib.

If we were certain that the $params parameter was always an array, then we can keep the method itself extremely simple and clean. We can ensure that by adding a pre-condition using ContractLib.

[code lang=”php”]
use Phix_ProjectContractLibContract;

class ActionToApply
{
public function appendNow($params)
{
Contract::Preconditions(function() use ($params)
{
Contract::RequiresValue(
$params,
is_array($params),
‘$params must be an array’
);
});

// original method code continues here
$params[] = time();
}
}
[/code]

Now, if someone passes in a non-array, the caller will automatically get an E5xx_ContractFailedException, which makes it clear that the fault is in the caller’s code … not your’s.

PHP 5.4’s upcoming support for better type-hinting is another way to catch this kind of error, but not only does ContractLib work today with PHP 5.3 (which means you don’t have to wait to migrate to PHP 5.4), but also that you can write tests for anything, not just the checking that’s built into PHP.

This means you can make your code much more robust, by tightening up on the quality of the parameter passed into your code by other programmers. To extend our example, we might decide that an empty array is also unacceptable:

[code lang=”php”]
use Phix_ProjectContractLibContract;

class ActionToApply
{
public function appendNow($params)
{
Contract::Preconditions(function() use ($params)
{
Contract::RequiresValue(
$params,
is_array($params),
‘$params must be an array’
);
Contract::RequiresValue(
$params,
count($params) > 0,
‘$params cannot be an empty array’
);
});

// original method code continues here
$params[] = time();
}
}
[/code]

The point here is that we can go way beyond type-hinting checks (important as they are) and look inside parameters to make sure they are suitable.

Here’s a real example from Phix’s CommandLineLib:

[code lang=”php”]
use Phix_ProjectContractLibContract;

class CommandLineParser
{
// …

public function parseSwitches($args, $argIndex, DefinedSwitches $expectedOptions)
{
// catch programming errors
Contract::Preconditions(function() use ($args, $argIndex, $expectedOptions)
{
Contract::RequiresValue(
$args,
is_array($args),
‘$args must be array’
);
Contract::RequiresValue(
$args,
count($args) > 0,
‘$args cannot be an empty array’
);

Contract::RequiresValue(
$argIndex,
is_integer($argIndex),
‘$argIndex must be an integer’
);
Contract::RequiresValue(
$argIndex,
count($args) >= $argIndex,
‘$argIndex cannot be more than +1 beyond the end of $args’
);

Contract::RequiresValue(
$expectedOptions,
count($expectedOptions->getSwitches()) > 0,
‘$expectedOptions must have some switches defined’
);
});

// method’s code follows on here …
}
}
[/code]

In this real-life code, we start off by checking for basic errors first (by making sure we’re looking at the right type for each parameter), and then we follow up with more specific tests, that ensure that we have data that we’re happy to work with. We’ve done these tests at the start of the method, so that it isn’t cluttered with error checking, which makes our code much cleaner that it might otherwise be. And, because all the tests are in one really easy to spot block, anyone reading your code can immediately see what they have to do to meet the contract you’ve created.

Because these tests are just plain-old PHP code, and don’t rely on annotations or any other such nonsense, the contracts you create and enforce are limited only by your choices.

But Aren’t All Those Tests Slow?

They are. PHP’s getting better and better at this, but function/method calls have always been painfully slow in PHP. I’m afraid that if you want robust code, you can’t have it for free. (You can in C, but that’s a topic to discuss over a decent whiskey at a conference).

I’ve done key two things with ContractLib to keep the runtime cost down:

  1. Contract::Preconditions() accepts a lambda function as its parameter. Your contract’s tests go inside this lambda function, and Contract::Preconditions() only calls the lambda function if contracts are enabled.
  2. By default, ContractLib does not enable contracts. You have to choose to do so by calling Contract::EnforceWrappedContracts().

This keeps the overhead down to just one method call (to Contract::Preconditions()) when contracts are not enabled. It isn’t as good as having no overhead, but it’s cheaper than the developer time lost trying to track down bugs in code that always assumes the caller can be trusted to do the right thing every time.

Any Questions?

I hope these examples have given you an idea on how to get started with ContractLib. If you have any questions or suggestions, please let me know, and I’ll do my best to answer them.

Be the first to leave a comment »

Introducing ContractLib

Posted by Stuart Herbert on January 11th, 2012 in 2 - Intermediate.

ContractLib is a simple-to-use PHP component for easily enforcing programming contracts throughout your PHP components. These programming contracts can go a long way to helping you, and the users of your components, develop more robust code.

ContractLib is loosely inspired by Microsoft Research’s work on the Code Contracts Library for .NET.

What Are Programming Contracts?

Programming contracts are tests around functions and methods, and they are normally used:

  1. to catch any ‘bad’ data that has been passed into the function or method from the caller, and
  2. to catch any ‘bad’ data generated by the function or method before it can be returned to the caller

These are pre-condition and post-condition tests, and they are tests that either pass or fail.

Why Have Programming Contracts?

Two reasons: code robustness and time saved.

Programming contracts catch errors early, and (unlike unit tests) they don’t just catch your errors, they catch errors made by programmers who reuse your code.

  • Catching errors early

    There is a class of bugs best described as garbage in, garbage out. The “garbage in” is data that is of the wrong type, or out of range, or missing (think empty arrays, empty strings, nulls). Often, the garbage being fed in is also garbage that has come out of a buggy function or method.

    Simple pre-condition checks at the start of your functions and methods quickly catches garbage data before it can propagate through your code. The more functions and methods contain pre-condition checks, the easier it becomes to catch garbage data closer to where it is being created. This allows you to spend less time tracking down the original source of a bug, and more time writing new code.

    These pre-conditions also greatly increase the chances of bugs in your code being caught in development, especially when combined with a healthy amount of unit testing.

    You can also add post-conditions at the end of your functions and methods, to make sure that you’re never returning any garbage back out of your function or method. There’s a lot of overlap between post-conditions and unit tests; the main difference is that your post-conditions will run 100% of the time, whereas your unit tests will only run when you run them and against the (often extremely limited) data you use in your unit tests.

  • Catching errors when code is reused

    Unit tests are great, and a very important part of creating high-quality code. But they’re your tests. They’re written to prove that your code does what you think it does.

    Unit tests don’t prove that someone else is reusing your code the way you meant them to.

    And neither do integration tests, because if someone is reusing your code, integration tests are their tests. Integration tests are tests to prove that they have glued their code on top of your code in a way that they are happy with.

    Simple pre-condition checks at the start of your functions and methods are your best opportunity to test how someone else is reusing your code, and to tell them if they’re getting it wrong.

Programming contracts are about building trust (just like unit tests). Code that you can trust is normally code that is quicker to work with. They’re really quick to write (normally far quicker than unit tests), and they can make it really quick to track down the origin of bugs in your code.

Don’t Programming Contracts Make Code Stupidly Strict?

An appropriate amount of strictness is a requirement of all high-quality code. The trick is knowing what to be strict about. Not strict enough, and you let in shitty data that causes your code to fail or be insecure. Too strict, and people will think that your code is too much trouble to work with.

As a general rule, pre-conditions should check for:

  • data that’s in an incorrect format
  • data that’s out of range
  • data that’s missing

Post-conditions should check the same things. They can also be used to check for data that should have been changed, but hasn’t been changed.

Aren’t Programming Contracts Too Old-Fashioned For PHP?

The concept has been around for decades. As a C programmer, I first learned about programming contracts in the early 90’s, when I was writing code that had to run for months at a time with zero downtime. We were debugging and improving code dating back from the 1980’s, and introducing programming contracts played an important role in getting to the bottom of many of the bugs that users reported.

PHP code (and other modern languages like Java, Ruby, Scala etc) is fundamentally similar to older languages like C, although you may not realise that this is the case. It’s the same fundamental paradigm – data is passed into blocks of software, and blocks of software may also pass data out too.

The advantage we have with PHP is that our programming contracts don’t have to be as lengthy as they would for a C program, because PHP itself can enforce type checks through type hinting, and we don’t have to worry about low-level details like proper handling of null-terminated strings.

Examples

You can take a look at ContractLib’s unit tests on GitHub.

I’ll post some detailed examples in my next blog post.

Be the first to leave a comment »

Phix 0.14 Released

Posted by Stuart Herbert on October 24th, 2011 in phix.

Phix v0.14 is now available from pear.phix-project.org.

What’s New In This Release

  • Snapshot versions of components – not ready to release a stable version of your component, but still need to publish your component to your PEAR channel for testing? You can now set the project.snapshot property in your build.properties file, and get non-stable packages for distribution.
  • Code coverage improvements – when you run phing test to run your component’s unit tests and generate the code coverage report, the code coverage report now automatically picks up all of your component’s PHP code, regardless of whether there is a test for it or not.
  • phpunit.xml support – phix now puts a phpunit.xml file inside your component, which includes all of the settings required to execute your component’s unit tests. This should help TextMate users a lot. This change was requested by attendees at the PHPNW11 conference.
  • More hooks in build.local.xml – for every target in your component’s build.xml file, you can now add “local.<target>” in build.local.xml, to perform any additional steps that you want to do. This feature was contributed by Martin Wernståhl.
  • Usability improvements – your component’s build.xml file now traps more errors than before, hopefully making it even easier to learn how to work with components.

How To Upgrade

To upgrade from an earlier release of Phix, please do the following:

sudo pear clear-cache
sudo pear upgrade phix/phix4componentdev

Once you’ve upgraded phix itself, don’t forget to go into each of your components, and run

phix php-library:upgrade .

to upgrade all of the skeleton files (build.xml et al) for your component.

What’s Coming In Phix 0.15

Phix 0.15 is all about making sure that Phix works as well on Windows as it already does on Linux and OSX. The feedback from the ZendCon session (which I was gutted to be unable to attend) was that there isn’t much needed, mostly setup instructions. Once that is done, we’ll continue to support Phix on Windows just as we already do on Linux and OSX.

Our roadmap for Phix 0.15 has all the details.

Be the first to leave a comment »

The PHP North West User Group ran it’s 4th (and largest yet!) PHP conference – PHPNW11 in Manchester last weekend.

My last set of photos from PHP North West 2011 are the odd ones out, the ones that didn’t really fit into any of the other sets.

I hope you’ve enjoyed my photos from the conference, and maybe – just maybe – they’ve made you think about going to a PHP conference somewhere near you in the near future.

Rob Allen

Derick Rethans

Jeremy Coates

So You Want To Be A Rockstar?

On The Way To The PHPNW11 Conference

Picadilly Gardens, Manchester

The Mothership Hovers

Opening The Call For Papers For PHPUK12

Cups of Tea

All Hail Our New Wifi Overlords!

Rick, Kerry, and Jenny Admire The Many Poses Of Jeremy Coates

Jeremy Coates - Magma Digital - PHPNW11 Organiser And Platinum Sponsor

Be the first to leave a comment »

The PHP North West User Group ran it’s 4th (and largest yet!) PHP conference – PHPNW11 in Manchester last weekend.

No conference – especially one as well-run as PHP North West – can happen without the small army of folks who give up their time to organise and staff the conference. I’m afraid that I didn’t manage to photograph everyone involved on the day (sorry!) but here’s to everyone who made PHP North West 2011 possible.

Jenny Wong

PHPNW11 Conference Organisers

PHPNW11 Conference Organisers

PHPNW11 Conference Organisers

PHPNW11 Conference Organisers

Jeremy Coates - Magma Digital - PHPNW11 Organiser And Platinum Sponsor

Lorna Jane and Jeremy Coates - PHPNW11 Conference Organisers

Be the first to leave a comment »

The PHP North West User Group ran it’s 4th (and largest yet!) PHP conference – PHPNW11 in Manchester last weekend.

This year, many of the sponsors were here not to drum up new business, but to hire new talent, continuing a trend from PHPUK11 earlier in the year. Sponsoring a conference is cheaper than paying traditional recruiters, with no shortage of motivated attendees to talk to.

Community tech conferences like PHP North West simply could not happen without the funds raised from the organisations who sponsor each conference. This short set of photos is my way, as a conference speaker, of saying thank you to every organisation who sponsored this year’s PHPNW conference.

PHPNW11 Conference Sponsors: Namesco

PHPNW11 Conference Sponsors: O'Reilly

PHPNW11 Conference Sponsors: ibuildings

PHPNW11 Conference Sponsors List

PHPNW11 Conference Sponsors List

PHPNW11 Conference Sponsors List

Be the first to leave a comment »
Page 4 of 19« First...23456...10...Last »

This Month

October 2018
M T W T F S S
« Sep    
1234567
891011121314
15161718192021
22232425262728
293031