Do you need Zend Framework training or consultancy? Get in touch!


Today is Ada Lovelace day which exists to highlight the many amazing and talented women in STEM. I'm bending the rules a little as I'm going to talk about Kathy today though she is not in STEM.

I've never known anyone so excited by what's new in technology.

She has always embraced technology to do her job better, she was one of the first in her office to be assigned a computer (back in the '80s!). Right from the beginning she could see that it would make her life easier and became an expert. Wherever she has worked, she has been the go-to person in the office for getting tech support. After she retired, she has continued to be so interested in computers and what they offer that she qualified to teach adult-education night classes in computing.

Over the years, her enthusiasm for tech has, if anything, increased. She has been an early adopter of every Microsoft operating system from Vista, all the way through to Window 10 as she is excited about what's next. I clearly remember her scorn at the idea of returning to Windows 7 as she was quite clear that the future was forwards, not backwards. She has also found time to investigate OS X and determine whether that operating system would improve her computing life or not. it didn't!

The smartphone revolution hasn't passed her by either. Firstly with Blackberries (for BBM) and now iPhones, Kathy has continued to ensure that she keeps up with the latest in mobile tech. Technology is there to make our lives easier and Kathy embraces it as fast as anyone that I know.

It's very easy to become jaded and take the tech around us for granted. It's also easy to assume that older people have less interest, however Kathy's enthusiasm for what's coming in the future inspires me.

The beginner's guide to rebasing your PR

You've successfully created a PR and it's in the queue to be merged. A maintainer looks at the code and asks you to rebase your PR so that they can merge it.

Say what?

The maintainer means that there have been other code changes on the project since you branched which means that your branch cannot be merged without conflicts and they would like to you to sort this out.

These are the steps you should take.


Read the summary.

1. Update your target branch from upstream

I assume you already have an upstream repository as described in The beginner's guide to contributing to a GitHub project. The target branch you want to update can be found at the top of the PR on the GitHub site.

For example:

Pr title

The target branch in this example is develop, though I see master a lot too.

$ git checkout develop
$ git pull upstream develop && git push origin develop

2. Rebase your branch

The next step is to change to your branch which is the other branch listed in the PR details (feature/validator-result-interface in this example) and then perform a rebase:

$ git checkout feature/validator-result-interface
$ git rebase develop

This will rewind all your commits on this branch and then replay them against the tip of the branch you are rebasing against.

As you have been asked to do this, you'll get conflicts. Don't panic!

$ git status will show you which files are in conflict. For each one, follow this process:

  1. Open in editor and search for "<<<<<<" (that's 6 <) to find the conflict
  2. Inspect and fix so that you end up with the correct text. Remove the lines starting with <<<<<<, ====== and >>>>>>.
  3. Press find-next in your editor to find the next conflict in the file.
  4. Once all conflicts in the file have been fixed, exit your editor
  5. Add this file to the staging index: git add {filename}
  6. Continue until git status shows that all conflicting files have been added to the index

Once all conflicting files are fixed you can continue the rebase:

$ git rebase --continue

3. Push your newly rebased branch to origin

Finally, all you need to do is push your branch back to origin. Note that this will require a force push and you've probably been told to never do such a thing. This is the one exception to that rule because the maintainer asked you to do it.

So go ahead:

$ git push -f origin

It's a good idea to leave a comment on the PR that you've done the rebase and the PR is ready for re-review.

All done

To summarise the steps required:

  1. $ git checkout {target branch}
  2. $ git pull upstream {target branch} && git push origin {target branch}
  3. $ git checkout {victim branch}
  4. $ git rebase {target branch}
  5. Fix conficts and continue rebasing
  6. $ git push -f origin

That's it. Being asked to rebase your PR isn't scary or (usually) difficult as long as you pay attention to what you're doing. However, if you're not fully comfortable with git, then I recommend buying the Git Workbook and working through all the exercises.

The beginner's guide to contributing to a GitHub project

This is a guide to contributing to an open source project that uses GitHub. It's mostly based on how I've seen Zend Framework, Slim Framework and operate. However, this is a general guide so check your project's README for specifics.


Skip to the summary.

Step 1: Set up a working copy on your computer

Firstly you need a local fork of the the project, so go ahead and press the "fork" button in GitHub. This will create a copy of the repository in your own GitHub account and you'll see a note that it's been forked underneath the project name:


Now you need a copy locally, so find the "SSH clone URL" in the right hand column and use that to clone locally using a terminal:

$ git clone

Which will do something like this:


Change into the new project's directory:

$ cd zend-validator

Finally, in this stage, you need to set up a new remote that points to the original project so that you can grab any changes and bring them into your local copy. Firstly clock on the link to the original repository – it's labeled "Forked from" at the top of the GitHub page. This takes you back to the projects main GitHub page, so you can find the "SSH clone URL" and use it to create the new remote, which we'll call upstream.

$ git remote add upstream

You now have two remotes for this project on disk:

  1. origin which points to your GitHub fork of the project. You can read and write to this remote.
  2. upstream which points to the main project's GitHub repository. You can only read from this remote.

Step 2: Do some work

This is the fun bit where you get to contribute to the project. It's usually best to start by fixing a bug that is either annoying you or you've found on the project's issue tracker. If you're looking for a place to start, a lot of projects use the "easy pick" label (or some variation) to indicate that this issue can be addressed by someone new to the project.


The number one rule is to put each piece of work on its own branch. If the project is using git-flow, then it will have both a master and a develop branch. The general rule is that if you are bug fixing, then branch from master and if you are adding a new feature then branch from develop. If the project only has a master branch, the branch from that. Some projects, like Slim use branches named after the version number (2.x and 3.x in Slim's case). In this case, pick the branch that's relevant.

For this example, we'll assume we're fixing a bug in zend-validator, so we branch from master:

$ git checkout master
$ git pull upstream master && git push origin master
$ git checkout -b hotfix/readme-update

Firstly we ensure we're on the master branch. Then the git pull command will sync our local copy with the upstream project and the git push syncs it to our forked GitHub project. Finally we create our new branch. You can name your branch whatever you like, but it helps for it to be meaningful. Including the issue number is usually helpful. If the project uses git-flow as zend-validator does, then there are specific naming conventions where the branch is prefixed with "hotfix/" or "feature/".

Now you can do your work.

Ensure that you only fix the thing you're working on. Do not be tempted to fix some other things that you see along the way as your PR will probably be rejected. Make sure that you commit in logical blocks. Each commit message should be sane. Read Tim Pope's A Note About Git Commit Messages.

Step 3: Create the PR

To create a PR you need to push your branch to the origin remote and then press some buttons on GitHub.

To push a new branch:

$ git push -u origin hotfix/readme-update

This will create the branch on your GitHub project. The -u flag links this branch with the remote one, so that in the future, you can simply type git push origin.

Swap back to the browser and navigate to your fork of the project ( in my case) and you'll see that your new branch is listed at the top with a handy "Compare & pull request" button:

Pr button

Go ahead and press the button!

If you see a yellow box like this:


Click the link which will take you to the project's CONTRIBUTING file and read it! It contains valuable information on how to work with the project's code base and will help you get your contribution accepted.

On this page, ensure that the "base fork" points to the correct repository and branch. Then ensure that you provide a good, succinct title for your pull request and explain why you have created it in the description box. Add any relevant issue numbers if you have them.

Create pr

If you scroll down a bit, you'll see a diff of your changes. Double check that it contains what you expect.

Once you are happy, press the "Create pull request" button and you're done.

Step 4: Review by the maintainers

For your work to be integrated into the project, the maintainers will review your work and either request changes or merge it.

Lorna Mitchell's article Code Reviews: Before You Even Run The Code covers the things that the maintainers will look for, so read it and ensure you've made their lives as easy as possible.

To sum up

That's all there is to it. The fundamentals are:

  1. Fork the project & clone locally.
  2. Create an upstream remote and sync your local copy before you branch.
  3. Branch for each separate piece of work.
  4. Do the work, write good commit messages, and read the CONTRIBUTING file if there is one.
  5. Push to your origin repository.
  6. Create a new PR in GitHub.
  7. Respond to any code review feedback.

If you want to contribute to an open source project, consider!

On blocking ads

There's been a discussion on Twitter this evening about ad-blockers now that Apple has enabled users of iOS to install ad-blocking plugins into their Safari browser. Note that this is not at the OS level and there is no default ad-blocker. The user has to choose to go to the App Store, install an ad-blocker app and then go to Settings->Safari and enable the app.

As we all know, Twitter isn't ideal for conversations requiring even a little bit of nuance, so I'm writing my thoughts here on my blog where I have more room!

Personally, I draw parallels with the older printed medium of a magazine. A magazine has adverts printed on the same physical piece of paper as the article and also comes with lots of separate ads that are inserted into the magazine. I think that reader of the magazine is free to remove the paper inserts without looking at them, put them in the bin and then read the magazine.

Translating to the web, I think that an ad that's served as part of the HTML from the web server is conceptually similar to being printed on the same piece of paper as the advert. Similarly, any ad that is served from a different server and inserted via JavaScript can be considered to be like an insert and may be removed without reading. This argument holds for me as the ad is distinct from the HTML content to such an extent that DNS may not even resolve to the other server or the user's web browser may not support JS (e.g. lynx) and the original article is still provided to the user. As such, an ad-blocker is conceptually the same as a personal assistant that removes the inserts before putting the magazine on the boss' desk. However, with computers, we can all afford a PA if we want one.

Hence, if you're an content producer and want to serve ads on the web, then serve them as HTML with your article and do not use JavaScript. If you do this, then your add will be visible to your readers as content blockers won't catch it.

In this particular case, I see it as no different from the Pop-ups section in Chrome:

Chrome pop-ups

Like ads served from a different domain, I see popups as "inserts", so I'm happy to have the browser not show them. Other people feel that disabling pop-ups interferes with the publisher's right to monetise and so allow all sites to show pop-ups.

It's all about where you draw the line.

Thanks @CalEvans, @codeguy, @Oramius & @JT_Grimes for the civilised discussion. Please feel free to continue the discussion via Twitter or write an article your own blog and ping back!

Simple Ansible file for Z-Ray preview

Recently, Zend made available a Z-Ray Technology Preview which takes the Z-Ray feature of Zend Server and makes it stand-alone.

This is very interesting as it means that I can run it with the PHP 5.6 on Ubuntu 14.04 LTS Vagrant set up that I prefer. I decided to create an Ansible playbook to install Z-Ray into my VM. The Z-Ray instructions are clear enough, so it was simply a case of converting them to a set of YAML steps as who wants to do manual installation nowadays?!

This is what I came up with:


- name: Downloading Z-Ray for PHP 5.6
    url: ""
    dest: "/home/vagrant/zray-php5.6-Ubuntu-14.04-x86_64.tar.gz"

- name: Extract Z-Ray archive
  unarchive: src=/home/vagrant/zray-php5.6-Ubuntu-14.04-x86_64.tar.gz dest=/opt copy=no creates=/opt/zray/INSTALL_ZRAY.TXT

- name: Set Z-Ray ownership
  shell: chown -R vagrant:vagrant /opt/zray

- name: Add the Z-Ray UI virtual host
  file: src=/opt/zray/zray-ui.conf dest=/etc/apache2/sites-available/zray-ui.conf

- name: Enable the Z-Ray UI virtual host
  shell: a2ensite zray-ui.conf

- name: Install Z-Ray PHP extension (Apache)
  file: src=/opt/zray/zray.ini dest=/etc/php5/apache2/conf.d/zray.ini state=link

- name: Install Z-Ray PHP extension (CLI)
  file: src=/opt/zray/zray.ini dest=/etc/php5/cli/conf.d/zray.ini state=link

- name: Link Z-Ray PHP 5.6 extension
  file: src=/opt/zray/lib/ dest=/usr/lib/php5/20131226/ state=link

I've set this up for PHP 5.6 which is what I'm using nowadays. If you're using 5.5, then you need to download zray-php5.5-Ubuntu-14.04-x86_64.tar.gz and the link needs to be to /usr/lib/php5/20121212/

Changing the file ownership to vagrant was important – I couldn't get it work without doing this step and I have no idea why its needed…

The standalone Z-Ray looks to be very similar to the one supplied as part of Zend Server and is equally as helpful in terms of getting a grip on what's going on with your application when developing it.

It has improved since I wrote about before and is even more useful now as it's been improved and has plugins!

With the standalone version of Z-Ray, there's really no excuse to not be using it.

Improved error handling in Slim 3 RC1

From RC1 of Slim 3, we have improved our error handling. We've always had error handling for HTML so that when an exception occurs, you get a nice error page that looks like this:

Slim3 error page

However, if you're writing an API that sends and expects JSON, then it still sends back HTML:

Slim3 old json error

At least we set the right Content-Type and status code!

However, this isn't really good enough. We should send back JSON if the client has asked for JSON. Until RC1, the only way to do this was to register your own error handler:

$c = $app->getContainer();
$c['errorHandler'] = function ($c) {
  return function ($request, $response, $exception) use ($c) {
    $data = [
      'code' => $exception->getCode(),
      'message' => $exception->getMessage(),
      'file' => $exception->getFile(),
      'line' => $exception->getLine(),
      'trace' => explode("\n", $exception->getTraceAsString()),

    return $c->get('response')->withStatus(500)
             ->withHeader('Content-Type', 'application/json')

which provides the correct output:

Slim 3 custom json error

However, we can do better than this and do it for you. Starting with RC1, Slim will now output JSON (or XML) when an error occurs if the client's Accept header is applcation/json (or application/xml) and it will also provide all the previous exception too. This is much nicer and also works for the two other error handlers: notFound and notAllowed.

Slim 3 rc1 error json

Finally, Note that you should never use our default errorHandler in production as it leaks too much data! We'll try and fix this before 3.0 final, though.

random_bytes() in PHP 5.6 and 5.5

Last week, I needed some random data and using the power of the PHP manual, came across random_bytes which does exactly what I need. However, it's PHP7 only.

As I target both Linux and Windows, I needed to do a bit more work to get it working which was fine, but a minor nuisance given that I know that there's a better way in PHP7.

Talking on the IRC channel a few days later, Anthony tells us about paragonie/random_compat which is a PHP 5.x polyfill for the PHP7 methods random_bytes() and random_int(). Usage is exactly the same, so when you switch to PHP7, you just remove the library from composer and all your code using these methods will continue to work.

I hadn't heard of it; I'm guessing that you haven't either, so now you know!

Slim-Csrf with Slim 3

In addition to the core Slim framework, we also ship a number of add-ons that are useful for specific types of problems. One of these is Slim-Csrf which provides CSRF protection.

This is middleware that sets a token in the session for every request that you can then set as an hidden input field on a form. When the form is submitted, the middleware checks that the value in the form field matches the value stored in the session. If they match, then the all is okay, but if they don't then an error is raised.

For the simplest use case, you need start the session and add the middleware:

$app->add(new Slim\Csrf\Guard());

Then, from within a given route callable, you can create your form and add two hidden fields: one for the token's name and one for its value:

$app->get('/', function ($request, $response, $args) {
    // CSRF token name and value
    $name = $request->getAttribute('csrf_name');
    $value = $request->getAttribute('csrf_value');

    // Render a form
    $html = <<<EOT
<!DOCTYPE html>
<head><title>CSRF test</title></head>
    <form method="POST" action="/process">
        <input type="hidden" name="csrf_name" value="$name">
        <input type="hidden" name="csrf_value" value="$value">
        <input type="text" name="name" placeholder="Name">
        <input type="submit" value="Go">

    return $response->write($html);

If you run this in a browser and view the source, you'll see something like this:

Slim csrf view source

Refresh and you see different values for the csrf_name and csrf_value fields, which means that the user can have multiple tabs open and submit without any issues.

For testing, I created a simple route callable:

$app->post('/process', function ($request, $response, $args) {
    return $response->write("Passed CSRF check.");

Pressing form's submit button will result in the display of "Passed CSRF check.". If you then refresh and confirm the post, you'll see "Failed CSRF check!" and the HTTP status code will be 400.

Customising the CSRF failure

It's likely that you'll want to customise the CSRF failure display as a plaint text error message isn't very user friendly! To change this, supply a callable to the Guard class which has the same signature as middleware: `
function($request, $response, $next). The middleware must return a Response.

This allows you to supply a custom error page:

$guard = new Slim\Csrf\Guard();
$guard->setFailureCallable(function ($request, $response, $next) {
    return $response->write(<<<EOT
<!DOCTYPE html>
<head><title>CSRF test</title></head>
    <p>An error occurred with your form submission.
       Please start again.</p>

As the failure callable has the middleware signature, you can also set a flag into $request and then deal with the CSRF failure later. The failure callable would look something like this:

$guard->setFailureCallable(function ($request, $response, $next) {
    $request = $request->withAttribute("csrf_result", 'FAILED');
    return $next($request, $response);

Now, your route callable can decide what to do:

$app->post('/process', function ($request, $response, $args) {
    if (false === $request->getAttribute('csrf_result')) {
        // Deal with error here and update $response as appropriate
    } else {
        // successfully passed CSRF check
        $response->write("Passed CSRF check.");
    return $response;

This is very powerful and remarkably easy to set up.


The flexibility of the failure callable allows you to handle a CSRF validation failure in the most appropriate way for your application and is a very powerful feature of this middleware.

As it's PSR-7 compliant, you can use the middleware independently of Slim with any PSR-7 middleware dispatch system that uses the middleware signature of function($request, $response, $next) where a Response is returned.

Using abstract factories with Slim 3

In my Slim 3 skeleton, I chose to put each action into its own class so that its dependencies are injected into the constructor. We then register each action with the DI Container like this:

$container['App\Action\HomeAction'] = function ($c) {
    return new App\Action\HomeAction($c['view'], $c['logger']);

In this case, HomeAction requires a view and a logger in order to operate. This is quite clear and easy. However, it requires you manually register each action class with the DI Container.

Bruno Skvorc said this on Twitter:

In short, this seems ULTRA wasteful if I want ALL my controllers to get view and logger.

Slim 3's default DI container is Pimple, which is one of the simpler DI Containers out there. To solve Bruno's problem, my initial though was to use Zend\ServiceManager's abstract factories feature.

Fortunately, Slim 3 supports container-interop and I've already written RKA\ZsmSlimContainer which integrates Zend\ServiceManager with Slim 3. Once we have ZSM in place it's all quite easy!

We need to register our own abstract factory with Zend\ServiceManager. An abstract factory requires two methods to be implemented: canCreateServiceWithName and createServiceWithName. The method names are fairly self-explantory.

In our case, canCreateServiceWithName needs to return true if the requested class name ends in "Action" and then createServiceWithName simply creates the class with the two required dependencies. It looks like this:


namespace App;

use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ActionAbstractFactory implements AbstractFactoryInterface
    public function canCreateServiceWithName(
        ServiceLocatorInterface $locator, $name, $requestedName)
        if (substr($requestedName, -6) == 'Action') {
            // This abstract factory will create any class that
            // ends with the word "Action"
            return true;
        return false;
    public function createServiceWithName(
        ServiceLocatorInterface $locator, $name, $requestedName)
        $className = $requestedName;

        // This factory creates Actions that have precisely two
        // constructor parameters: $view & $logger
        $view = $locator->get('view');
        $logger = $locator->get('logger');
        return new $className($view, $logger);

We then register the abstract factory with the DI container:

$container->addAbstractFactory(new App\ActionAbstractFactory());

The end result is that we don't need to register every Action with the DI Container individually as long as they all have the same constructor signature. This is obviously a simplistic example, but the principle applies to any situation where you need to create different classes in the same vein.

If you want to see this in action, I've created a sample project on GitHub.

Zend\Input fallback value

Recently an issue was reported against Zend\InputFilter where the reporter has discovered a regression where the fallback value wasn't being populated correctly. Matthew investigated, fixed it and asked me to review it.

I was fascinated as I didn't realise (or had completely forgotten!) that Zend\Input and Zend\InputFilter supported fallback values so I looked into it and it turns out that it's simple and works exactly as its name implies.

For the basic case of using an Input directly, you use it like this:

$name = new \Zend\InputFilter\Input('name');
$validators = $name->getValidatorChain();
$validators->addValidator(new \Zend\Validator\StringLength(5), true);

$name->setFallbackValue('Rob Allen');

$isValid = $name->isValid();

The output is "Rob Allen".

That is, when the value supplied is empty, then, the fallback value is set instead and used.

A wrinkle

There is, however, a wrinkle! Sometimes $name->getValue() returns an empty string and this occurs due to particular combinations of required, allow_empty & continue_if_empty as I've already discussed.

If continue_if_empty is false then the combination of required & allow_empty affects whether you get the fallback value or an empty string when calling getValue() after isValid():

required allow_empty What happens
true false With an empty value, the fallback value is returned in getValue().
true true The fallback value is ignored and an empty value is returned in getValue().
false false The fallback value is ignored and an empty value is returned in getValue().
false true The fallback value is ignored and an empty value is returned in getValue().

If you compare this table to the one in the last post, you'll notice that in the three cases where the validators are not run, the fallback value is not set. This is not surprising as those combinations result in a short-circuit of isValid().

Test app

Again, I used a test application to check this out

require 'vendor/autoload.php';

$values = [
    // [contine_if_empty, required, allow_empty]
    [false, true, false],
    [false, true, true],
    [false, false, false],
    [false, false, true],
    [true, true, false],
    [true, true, true],
    [true, false, false],
    [true, false, true],

foreach ($values as $row) {

function test($continueIfEmpty, $required, $allowEmpty)
    // set up Input with a StringLength validator so we'll know if the
    // validators have run as they will always fail
    $name = new \Zend\InputFilter\Input('name');
    $validators = $name->getValidatorChain();
    $validators->addValidator(new \Zend\Validator\StringLength(5), true);

    $name->setFallbackValue('Rob Allen');


    // Test
    echo "continue_if_empty: " . (int)$continueIfEmpty;
    echo ", required: " . (int)$required;
    echo ", allow_empty: " . (int)$allowEmpty;
    $isValid = (int)$name->isValid();
    echo " - Result: isValid() = $isValid";
    if (!$isValid) {
        echo " " . current($name->getMessages());
    } else {
        echo ", value = " . $name->getValue();
    echo "\n";

As before, this app simply runs through all combinations of required, allow_empty & continue_if_empty against a Zend\InputFilter\Input with a fallback value set and sees what happens.

This is the output:

$ php test.php 
continue_if_empty: 0, required: 1, allow_empty: 0 - Result: isValid() = 1, value = Rob Allen
continue_if_empty: 0, required: 1, allow_empty: 1 - Result: isValid() = 1, value = 
continue_if_empty: 0, required: 0, allow_empty: 0 - Result: isValid() = 1, value = 
continue_if_empty: 0, required: 0, allow_empty: 1 - Result: isValid() = 1, value = 
continue_if_empty: 1, required: 1, allow_empty: 0 - Result: isValid() = 1, value = Rob Allen
continue_if_empty: 1, required: 1, allow_empty: 1 - Result: isValid() = 1, value = Rob Allen
continue_if_empty: 1, required: 0, allow_empty: 0 - Result: isValid() = 1, value = Rob Allen
continue_if_empty: 1, required: 0, allow_empty: 1 - Result: isValid() = 1, value = Rob Allen\


Note that with the fix discussed at the start of this post, Zend\InputFilter works exactly the same as Zend\Input, as you'd expect. This fix was back ported to the 2.4 release too, so if you are using fallback values, ensure that you're using the latest 2.4 or 2.5 version.


If you want to use a fallback value with Zend\Input make sure that you set required to true and allow_empty to false. Fortunately this is the default, so that's probably what you're doing anyway!