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

DI Factories for Slim controllers

When using classes for route actions in Slim 3, I recommend using a single class for each route. However you can use a single class for multiple routes.

To register a class method to a route you pass a string as the route callable where the class name is separate from method by a colon like this:

$app->get('/list', 'MyController:listAction');

Slim will retrieve MyController from the DI container and then call the listAction method using the usual signature:

function (Request $request, Response $response, $args = []) : Response;

If you don't specify a method, then Slim will see if it treat the class as a callable, so you can implement __invoke() and then register the route like this:

$app->get('/list', 'MyController');

and Slim will call MyController::__invoke() for you.

Writing a DI factory for your class

Usually, your controller action will need some dependencies in order to work, such as access to a service layer class, or ORM's entity manager.

To handle this, you should inject the dependency in your controller's constructor by writing a factory for the DI container. This sounds scary and complicated, but a factory is just another way of saying "a function that instantiates an object". This is the simplest DI container factory we can write for MyController:

// Retrieve container instance
$container = $app->getContainer();

// Register MyController
$container['MyController'] = function ($c) {
    return new MyController();

The closure is the factory and as you can see, it simply returns an new instance of MyController. It is registered with Slim's default DI container by assigning the closure to an array key (['MyController']) and it is vital that the string you use here is the same as the string you use before the colon in the route configuration ('MyController:list'.

Injecting the dependencies

To inject the dependencies, we register them with the DI container too as factories and then retrieve them in our controller factory.

Firstly, register a dependency:

$container['DatabaseService'] = function ($c) {
    return new DatabaseService();

Now we can use this in our controller factory. To do this note that the factory closure has a parameter, $c, which is the DI container itself. This means we can retrieve anything that's registered with the DI container by using the get() method.

Hence we update our controller factory like this:

$container['MyController'] = function ($c) {
    $dbService = $c->get('DatabaseService');
    return new MyController($dbService);

The MyController constructor now receives our dependency and can store it to a class property ready for use in the route action method like this:

final class MyController
    private $dbService;
    public function __construct($dbService)
        $this->dbService = $dbService;

    public function listAction($request, $response, $args)
        $dataArray = $this->dbService->fetchData();
        return $response->withJson($dataArray);

There are numerous advantages to doing this. The main one for me is that there are no surprise dependencies any more. You can look at the constructor and know exactly which classes this class needs to do its job. You can also test it more easily which is beneficial!

I prefer to use one class for each route action as I can ensure that the dependencies that are injected are the correct ones for this action. When using multiple action methods in a controller class, you start needing to inject classes that are only used for just one or two of the actions and this is inefficient, especially if those dependencies are relatively expensive to construct. There are ways around this if you use a more powerful DI container such as Zend-ServiceManager though.

Easily install Swift on Linux

This is the simplest set of steps that I've found so far in order to get Swift on (Ubuntu) Linux. Essentially, you can download a snapshot and you're good to go.

If you're not already on Ubuntu 15:10, create a VM. Vagrant is an easy way to do this:

$ vagrant init ubuntu/wily64
$ vagrant up
$ vagrant ssh

Install the dependencies:

$ sudo apt-get install clang libicu-dev vim

(Vim isn't an actual dependency, but I can't cope with terminal that doesn't have it!)

Grab a Swift snapshot & untar:

$ cd ~
$ curl -O
$ mkdir swift
$ tar xzf swift-DEVELOPMENT-SNAPSHOT-2016-04-12-a-ubuntu15.10.tar.gz -C swift --strip-components 1

I've used the latest snapshot as of this writing: check the website for the latest one as it is updated regularly.

The binaries are now in ~/swift/usr/bin, so add that to your path and you're good to go:

$ echo 'export PATH=~/swift/usr/bin:$PATH' >>~/.profile
$ source ~/.profile

Prove it works:

$ swift --version
Swift version 3.0-dev (LLVM 752e1430fc, Clang 3987718dae, Swift 36739f7b57)
Target: x86_64-unknown-linux-gnu

Now, you just need to learn Swift!

Unit testing with Swift PM

As I tend to work with Swift on Linux, I've been working out how to unit test using the Swift Package manager. This article is my way of remembering what I've learnt so far! Let's do this in the context of writing an a Todo entity from the Todo-Backend project.

Create a package

Creating a package is easy with Swift PM:

mkdir Todo
cd Todo
swift build --init library

(you can replace library with executable when creating an app)

When you run this, Swift PM will create the following:

├── Package.swift
├── Sources
│   └── Todo.swift
└── Tests
    ├── LinuxMain.swift
    └── Todo
        └── Todo.swift

Your Swift source files go in Sources and your unit tests go in Tests.

A simple Todo object

Inspecting the Todo-Backend test suite, we can see that a todo item has the following properties:

  • title: a string
  • completed: a boolean
  • order: an integer

Let's build that in Swift and we'll put it in Sources/Todo.swift:

public struct Todo {
    let title: String
    let completed: Bool
    let order: Int
    init(title: String, completed: Bool, order: Int) {
        self.title = title
        self.completed = completed
        self.order = order

I've chosen to implement this as a value object so that title, completed and order cannot be changed after initialisation. If we need to change them, we'll create a new object from the information in this one.

Setup the unit test code

SwiftPM automatically creates two files for us in the Tests directory: LinuxMain.swift which is a list of all the unit test classes in our package and Todo/Todo.swift which is our test class. Interestingly, the test class extends our main class, which is a fairly common pattern in Swift.

Swift and Swift Package Manager are both under heavy development and not always in sync with each other. With the 12th April 2016 build of Swift 3.0, the skeleton files created by Swift PM for running the tests under Linux are wrong! Let's rewrite them.

Firstly, I prefer my unit test class to be separate, so delete Tests/Todo/Todo.swift and create Tests/Todo/TodoTests.swift. This file holds our unit test class, and we'll write a simple unit test to get us started:

import XCTest
@testable import Todo

class TodoTests: XCTestCase {
	func testInitSetsTitle() {
        let todo = Todo(title: "test", completed: false, order: 1)
        XCTAssertEqual(todo.title, "test", "Incorrect title")

Our unit test method is testInitSetsTitle and it simply instantiates a Todo and then uses XCTAssertEqual to check that the title of the object matches the string that we set.

Linux specific additions

To test under Linux, we need to do two things. Firstly we need to provide a list all the unit test methods in the test class as a static variable and secondly we need to list our test classes in a file called LinuxMain.swift.

To do the first bit, we add an extension to TodoTests within Tests/Todo/TodoTests.swift:

#if os(Linux)
extension TodoTests {
	static var allTests : [(String, TodoTests -> () throws -> Void)] {
		return [
			("testInitSetsTitle", testInitSetsTitle),

This block extends the TodoTests class solely for Linux to add a static variable called allTests which is a an array of tuples consisting of the name of the test and the test's method name. By convention, the string name is the same as the actual function name as it seems to be used by the test runner as a label.

Secondly we create Tests/LinuxMain.swift. This file was created by Swift PM, but as I said earlier is wrong, so needs to be replaced with:

import XCTest
@testable import TodoTestSuite


This file simply instantiates XCTMain with a list of testCases for each test class' allTests variable. This is another thing that really should be sorted via a build system by the time Swift 3 goes stable… As it is today though, it's not hard to keep it updated.

Running the unit tests

To run the unit tests, we simply build the project with swift guid and then run swift test:

$ swift build
Compiling Swift Module 'Todo' (1 sources)

$ swift test
Compiling Swift Module 'TodoTestSuite' (1 sources)
Linking .build/debug/test-Package
Test Case 'Todo.testExample' started.
Test Case 'Todo.testExample' passed (0.0 seconds).
Executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.005) seconds
Total executed 1 test, with 0 failures (0 unexpected) in 0.0 (0.005) seconds

That's it

That's all there is to unit testing in Swift under Linux. There's not a lot of documentation yet, but I found Apple's Writing Test with Swift documentation handy.

Other useful reading is SE-0019: Swift Testing is also worth reading as that documents how testing is implemented in Swift PM and the Additional Considerations for Swift on Linux document in the swift-corelibs-xctest repository.

Overriding Slim 3's error handling

Slim 3 registers two error handers:

This means that if you want to override the default error handlers, you need to override both error handlers with your own code.

Each error handler is a callable. The signatures are:

  • errorHandler: function ($request, $response, $exception)
  • phpErrorHandler: function ($request, $response, $error)

To override a error handler, simply register a new callable with the Container:

$container = $app->getContainer();

$container['errorHandler'] = function ($container) {
    return function ($request, $response, $exception) use ($container) {
        // retrieve logger from $container here and log the error
        return $response->withStatus(500)
                        ->withHeader('Content-Type', 'text/html')
                        ->write("Oops, something's gone wrong!");

$container['phpErrorHandler'] = function ($container) {
    return function ($request, $response, $error) use ($container) {
        // retrieve logger from $container here and log the error
        return $response->withStatus(500)
                        ->withHeader('Content-Type', 'text/html')
                        ->write("Oops, something's gone wrong!");

If you don't want to repeat yourself, you can register the `phpErrorHandler` like this:

$container['phpErrorHandler'] = function ($container) {
    return $container['errorHandler'];

Note that you can register any PHP callable, so a class with an __invoke() method also works.

Handling PHP notices

As an aside, Slim 2's error handler catches PHP notices for you (which can be infuriating or very useful!). Slim 3 doesn't do this by default, so if you want to catch PHP notices then you need to register your own error handler like this:

set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting, so ignore it
    throw new \ErrorException($message, 0, $severity, $file, $line);

That's all there is to it.

Using Eloquent in Slim Framework

Eloquent is one of the easier ORMs to get started with, so let's look at how to use and test it within a Slim Framework application.

Set up

You can add Eloquent to your Slim project via composer:

composer require illuminate/database

You now need to bootstrap it. To do this we need some settings, so lets do that in our standard Slim configuration:

$config = [
    'settings' => [
        'db' => [
            // Eloquent configuration
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'bookshelf',
            'username'  => 'rob',
            'password'  => '123456',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',

We then instantiate the capsule manager and boot Eloquent , probably in index.php:

$container = $app->getContainer()
$capsule = new Illuminate\Database\Capsule\Manager;

From this point, you can simply follow the documentation to create your Eloquent models and use them within your route callables.

Testing your models

At first glance, it seems quite hard to test your models as the find method is a static.

For example, consider this route callback within an action class:

public function __invoke($request, $response, $args)
    return $this->view->render($response, 'author/list.twig', [
        'authors' => Author::all(),

To test it, I followed a tip from Taylor Otwell and wrapped the find method in a class that I could then mock:

namespace Bookshelf;

class AuthorRepository
    public function all()
        return Author::all();

    public function find($id, $columns = ['*'])
        return Author::find($id, $columns);

The callback then becomes:

public function __invoke($request, $response, $args)
    return $this->view->render($response, 'author/list.twig', [
        'books' => $this->authorRepository->all()

Like the view, the authorRepository is injected into the constructor and so can be mocked out. The full class looks like this:

namespace Bookshelf;

use Slim\Views\Twig;
use Bookshelf\AuthorRepository;

final class ListAuthorsAction
    private $view;
    private $authorRepository;

    public function __construct(
        Twig $view,
        AuthorRepository $authorRepository
    ) {
        $this->view = $view;
        $this->authorRepository = $authorRepository;

    public function __invoke($request, $response, $args)
        return $this->view->render($response, 'author/list.twig', [
            'authors' => $this->authorRepository->all()

To test using PHPUnit, we start by creating a mock for the AuthorRepository:

$authorRepository = $this->getMockBuilder(AuthorRepository::class)

Then we set the expectation that the all method will return a collection of Authors:

use Illuminate\Database\Eloquent\Collection;
$authors = new Collection([
    new Author(['name' => 'test1']),
    new Author(['name' => 'test2']),
    new Author(['name' => 'test3']),


We do the same for the view object:

$view = $this->getMockBuilder(Twig::class)

$response = new Response();
$response->write('Rendered text on page');

    ->with($response, 'author/list.twig', ['authors' => $authors])

Now we can instantiate the action class with our two mock objects. We then create a request and response objects and run the action and test the returned response:

$action = new ListAuthorsAction($view, $authorRepository);
$request = Request::createFromEnvironment(Environment::mock());
$response = new Response();

$ReturnedResponse = $action($request, $response);

$this->assertSame((string)$ReturnedResponse->getBody(), 'Rendered text on page');


Eloquent is quite a nice implementation of the Active Record pattern. If that meets your needs, then it is easy to use within a Slim Framework application, so go for it!

Free the Geek appearance

I was delighted to spend an hour chatting with Matt Setter on episode 14 of Free the Geek. In this podcast, we talked about Slim 3 and development in general.

Matthew gives me a great introduction (thanks!) and then we delve into the chat.

We talk about the importance of semantic versioning as I think this is key to stability in a project. It's not very glamorous to work on code where you have to maintain backwards compatibility, but it is vital to the success of a library such as Slim Framework. Developers who use your library depend on it and semantic versioning is the way to ensure that no-one is surprised. I hate it when a library I use has BC break between patch or minor version numbers that results in my software breaking, so I try not to break the contract in Slim. Of course, sometimes we've introduced a BC break by accident, but when we have, we've fixed it immediately.

We also spoke about software architecture and how important it is to make the right decisions for your project and the team building it. Projects have a lifecycle and it's useful to build appropriately for the stage that your project is at. I'm a fan of architecting for the near term with an eye to the likely long term paths and ensuring that your design fits the project.

We talk about this and more, so have a listen.

A few composer tips

I recently learned about a couple of features of composer that I thought I'd write down here so that I don't forget them! I also had to deal with a conflict in composer.lock recently, so I've noted down how I solved that too.

List installed versions

To list the current versions of all installed dependencies:

composer show -i 

The output looks something like:

container-interop/container-interop 1.1.0  Promoting the interoperability of container objects...
monolog/monolog                     1.17.2 Sends your logs to files, sockets, inboxes, ...
nikic/fast-route                    v0.6.0 Fast request router for PHP
pimple/pimple                       v3.0.2 Pimple, a simple Dependency Injection Container
psr/http-message                    1.0    Common interface for HTTP messages
psr/log                             1.0.0  Common interface for logging libraries
slim/php-view                       2.0.6  Render PHP view scripts into a PSR-7 Response...
slim/slim                           3.1.0  Slim is a PHP micro framework that helps you...

Very useful for working out exactly what's installed.

Set PHP version

To set the version of PHP that composer will use to resolve dependencies, add this to your composer.json file:

    "config": {
        "platform": {
            "php": "5.6.19"

You can now run composer update on a PHP 7 installation and it will create a composer.lock file suitable for a server running PHP 5.6.19.

Resolving a conflict in composer.lock

When you merge a feature branch into develop and get a conflict in composer.lock, I've found these strategies work best for me:

Just the hash

If the only conflict is in the "hash" and "content-hash" lines, then pick either choice and then run:

composer update --lock

Any other conflict

For any other conflict where you want to keep the current set of versions on develop:

  1. Retrieve the correct lock file for develop: git merge --ours
  2. Add in each new dependency in the merged composer.json that's not in the original develop's composer.json using
    composer require {vendor/package}

The end result is a composer.lock file with the original information from develop along with the new packages from the feature branch.

Configuration in Slim Framework

Configuration in Slim Framework is nice and simple: the App's constructor takes a configuration array for the DI container;

$config = [];
$app = new Slim\App($config);

Setting up

The settings sub-array is used to hold the settings of your application:

$config = [
    'settings' => [
        'displayErrorDetails' => true,

        'logger' => [
            'name' => 'slim-app',
            'level' => Monolog\Logger::DEBUG,
            'path' => __DIR__ . '/../logs/app.log',
$app = new Slim\App($config);

Slim comes with a number of settings that you can change. The most important is displayErrorDetails. This defaults to false, but if you set it to true, then it will display the details of any exceptions when rendering an error page. Ensure that this is set to false in production!

You can put any other settings you want to in the configuration, under any name you like as I have done with the logger key, which contains information about how to configure a Monolog instance.

Retrieving settings

The settings are stored in the DI container so you can access them via the settings key in container factories. For example, I can set up a container factory for to create my Monolog instance like this:

$container = $app->getContainer();
$container['logger'] = function ($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    return $logger;

Slim's default container is Pimple, so we use the array notation to register a new service called 'logger' in this case. The logger settings are retrieved using $settings = $c->get('settings')['logger'].

Separate file for configuration

You should use a separate file for your configuration. This is most easily done using require. Firstly, we create config.php and return the configuration array from it:



return [
    'settings' => [
        'displayErrorDetails' => true,

        'logger' => [
            'name' => 'slim-app',
            'level' => Monolog\Logger::DEBUG,
            'path' => __DIR__ . '/../logs/app.log',

As require returns whatever the included file returns, we load like this:

$config = require 'config.php';
$app = new \Slim\App($config);

Environment variables using dotenv

Consider using environment variables for the differences between servers. These can be configured as part of your apache/nginx setup or you can use dotenv.

In this case, create a .env file and add it to .gitignore:



We can use these environment variables in our configuration file via getenv:



return [
    'settings' => [
        'displayErrorDetails' => (bool)getenv('DISPLAY_ERRORS'),

        'logger' => [
            'name' => 'slim-app',
            'level' => (int)getenv('LOG_LEVEL') ?: 400,
            'path' => __DIR__ . '/../logs/app.log',

We then load using:

$dotenv = new Dotenv\Dotenv(__DIR__);
$config = require 'config.php';
$app = new \Slim\App($config);

Multiple configuration files

You may also want to split your configuration into multiple files which are then merged together with files loaded later overriding the settings from previous files.

One use case is to have a local.config.php that's not in git that contains per-server configuration to be merged with your master configuration in config.php.

For example, your live configuration should turn off display of errors and maybe set a different logging level:


return [
    'settings' => [
        'displayErrorDetails' => false,

        'logger' => [
            'level' => Monolog\Logger::ERROR,

Merging the two arrays is a little complicated as array_merge_recursive doesn't do what you expect and will result in the 'displayErrorDetails' key becoming an array with two elements. You could write your own merge method, but it's easier to use zend-stdlib's merge method:

$config = require 'config.php';
$localConfig = require 'local.config.php';
$config = Zend\Stdlib\ArrayUtils::merge($config, $localConfig);
$app = new \Slim\App($config);

Ini/Yaml/JSON/XML configuration

If you want to use something other than PHP arrays, then use zend-config along with glob. In this case, you place all your configuration files in a single directory, such as config/ and then name them with .global.{type} and .local.{type} to control order.

For example, to load the configuration files global.yaml, and then local.yaml in that order:

$config = Zend\Config\Factory::fromFiles(glob('config/{global, *.global, local}.*', GLOB_BRACE));

One useful feature of zend-config is that you can mix and match between formats, so local.yaml could be local.ini and it would still work.


As you can see, using configuration with Slim is very easy; all the choices come down to how you want to organise your configuration so that you can manage the differences between environments easily.

Testing Slim Framework actions

To test a Slim Framework action, you need a request and a response object and mock whatever is in the action. This is one way to do this.

Consider this simple echo action that returns the query parameters to you as a JSON encoded string:

$ curl "http://localhost:8888/echo?foo=bar&this=that"

This is one of those useful API endpoints that your users can use to check that everything is working as expected.

The action under test

The code for this endpoint is a class called EchoAction which looks like this:

namespace App\Action;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class EchoAction
    public function __invoke(Request $request, Response $response, $args = [])
        return $response->withJson($request->getQueryParams());

and it is registered with the Slim App like so:

$app->get('/echo', App\Action\EchoAction::class);


Testing it isn't too complex as there are no dependencies on the EchoAction class itself, so we just have instantiate the class, invoke it and write an test.

For a URL of the form /echo?foo=bar, the core test code is:

$action = new \App\Action\EchoAction();
$response = $action($request, $response);
$this->assertSame((string)$response->getBody(), json_encode(['foo' => 'bar']));

Creating the request and response

Creating the $response is easy as the constructor parameters all have defaults:

$response = new \Slim\Http\Response();

The $request is a little more complex as it's constructor signature looks like this:

public function __construct(
        UriInterface $uri,
        HeadersInterface $headers,
        array $cookies,
        array $serverParams,
        StreamInterface $body,
        array $uploadedFiles = []

However, Slim actually creates a Slim\Http\Request using the static createFromEnvironment() factory method, which takes a Slim\Http\Environment instance. Roughly, it does this:

$request = Request::createFromEnvironment(new Environment($_SERVER));

Setting up a $_SERVER array with the relevant elements can be a little tiresome in testing though. Fortunately, Josh needed to test Slim itself, so the Environment object has a handy static method called mock() that does this for us.

We use it like this:

$environment = \Slim\Http\Environment::mock([
    'REQUEST_URI' => '/echo',

As you can see, mock() takes an array which contains $_SERVER keys that we wish to set up for our particular test. Usually we set the REQUEST_METHOD, REQUEST_URI and, if we need it, QUERY_STRING. We need QUERY_STRING as this is the key in $_SERVER that Request uses to determine the query parameters for the request.

Putting it all together

Hence, our completed test looks like this:

class EchoActionTest extends \PHPUnit_Framework_TestCase
    public function testGetRequestReturnsEcho()
        // instantiate action
        $action = new \App\Action\EchoAction();

        // We need a request and response object to invoke the action
        $environment = \Slim\Http\Environment::mock([
            'REQUEST_METHOD' => 'GET',
            'REQUEST_URI' => '/echo',
        $request = \Slim\Http\Request::createFromEnvironment($environment);
        $response = new \Slim\Http\Response();

        // run the controller action and test it
        $response = $action($request, $response, []);
        $this->assertSame((string)$response->getBody(), '{"foo":"bar"}');

All in all, it's not too complicated to test a Slim action and Environment::mock() makes it easy to set up particular test cases.

Determining the image type of a file

One thing I learnt recently which I probably should have known already is that getimagesize() returns more than just the width and height of the image.

I've always used it like this:

list($width, $height) = getimagesize($filename);

However, getimagesize() also returns up to 5 more pieces of information.

Interestingly, the data array is a mix of indexed elements and named elements For example, for a file I uploaded while testing a PR, the output of print_r(getimagesize($filename)) is:

    [0] => 1440
    [1] => 1440
    [2] => 3
    [3] => width="1440" height="1440"
    [bits] => 8
    [mime] => image/png

A very strange decision when designing the response of this function!

Index 2 is the file type which is an "IMAGETYPE" constant, such as IMAGETYPE_PNG. Note that there's also a constant called IMG_PNG, but this is a different number, so make sure you use the right one!

This is useful for file uploads. Consider this data in $_FILES:

    [image] => Array
            [name] => myimage
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpbGyIq7
            [error] => 0
            [size] => 90410


In this case, there is no extension on the uploaded filename and the type is application/octet-stream. If I want to resize this image using gd, then I'm going to need to know whether to use imagejpeg, imagegif or imagepng. A simple way to do this is something like this:

list($width, $height, $imageType) = getimagesize($filename);

// create $smallImage using imagecreatetruecolor() and imagecopyresampled(), etc.

// save image
switch ($imageType) {
        imagejpeg($smallImage, $event_image_path . $small_filename);
        imagegif($smallImage, $event_image_path . $small_filename);
        imagepng($smallImage, $event_image_path . $small_filename);
        throw new Exception("Unable to deal with image type");

It's easier than dealing with the type from $_FILES too and by writing it down, maybe I'll remember it.