Developing software in the Real World

Run Slim 2 from the command line

If you need to run a Slim Framework 2 application from the command line then you need a separate script from your web-facing index.php. Let's call it bin/run.php: bin/run.php:

We set the script to be excutable and then we can then run it like this:

and the output is, as you would expect:

This works by converting the command line parameters into the URL path for Slim to route by imploding $argv… continue reading.

Routing to a controller with Slim 2

In a couple of projects that I've written using Slim Framework 2, I've found it beneficial to organise my code into controllers with injected dependencies; probably because that's how I'm used to working with ZF2. To make this easier, I've written an extension to the main Slim class and packaged it into rka-slim-controller which will dynamically instantiate controllers for you for each route. Defining routes is exactly the same as normal for a Slim controller,… continue reading.

Dependency injection in Slim framework 2

Slim framework comes with a Dependency Injection container called Set. The basics The DIC is accessed via the container property of $app. To set, you use the set() method:

If you need a given resource to be shared, then use the singleton method:

And then to retrieve from the container, there are multiple ways to do it:

The shortcut version ($app->foobar) only works if the key is a valid PHP variable name.… continue reading.

Using ZF2 Forms with Twig

Following on from looking at how to integrate Zend Framework 2 forms into Slim Framework, let's look at the changes required if you also happen to want to use Twig. When it comes to rendering the form, we would want our template to look like this:

The ZF2 view helpers, formRow and formElement now look like Twig functions, however we don't want to have to rewrite all our ZF2 view helpers into Twig. Fortunately,… continue reading.

Redirecting in Slim 2 Middleware

I recently ran into a problem with calling redirect() in a Slim Framework 2 middleware class, so I thought I'd better document the solution so that I remember in future! The authentication middleware looks roughly like this:

The problem is that you can't call $app->redirect() in Middleware as redirect() is designed to only run in application route callbacks and Middleware should only act on the request and response objects. This is because the app's… continue reading.

Integrating ZF2 forms into Slim

Let's say that you want to use Zend Framework 2's Form component outside of ZF2 itself. In this case, a Slim application. It turns out that Composer makes this quite easy, though there's quite a lot of code involved, so this is a long article. Start with a really simple Slim Application. index.php:


and of course, composer.json:

Given this starting point, we can now add Zend\Form. Firstly, we update composer.json:

continue reading.