Using controllers with SlimPHP

30 Jan 2017 in Tech

Now that we have multiple routes in our application, we have an excuse to start splitting our controller logic out into multiple files.

According to the documentation, there are a few ways to accomplish what we're trying to do:

  • container_key:method

  • Class:method

  • An invokable class

  • container_key

Don't worry if those don't make sense at the moment. We're going to choose the container_key:method option as it gives us the most flexibility. What this means, is that we're going to store a reference to the class we want to use as a controller in the container, then reference it later.

We'll move this later, but for now create a class called HomeController in public/index.php just before the line $container = new \Slim\Container;. It should look like the following:

php
class HomeController {
protected $view;
public function __construct($view) {
$this->view = $view;
}
public function hello(Request $request, Response $response) {
return $this->view->render($response, 'index.html', [
"name" => "Michael"
]);
}
}

The class has a constructor which receives a reference to the view system that we want to use (Twig) and saves it for later. Then, it has a hello function which looks very similar to our old route function.

The next thing to do is to register this controller with our container so that we'll be able to use it. To do this, we add it to the $container variable just before we instantiate our application. Before the line that says $app = new \Slim\App($container);, add the following:

php
$container['controller.home'] = function($container) {
return new HomeController($container['view']);
};

Once this is done, $container['controller.home'] will point to our controller. Finally, we have to update our route to point to this new controller. Edit $app->get('/') so that it looks like the following:

php
$app->get('/', "controller.home:hello");

What this means, is that Slim will look for something in the container called controller.home (and it'll find our controller as we registered it earlier), then it'll try and call the hello function on that class.

If you run the PHP server with php -t public -S localhost:8000 and visit http://localhost:8000 once again, you should see the home page just like normal.

Congratulations! You've updated your Slim application to use a controller rather than an anonymous function for a route. Although this is a little better, all of the code is still in index.php and is looking a bit messy. We'll cover how to split this into multiple files in the next post.