no-framework-tutorial/07-inversion-of-control.md
2016-04-03 02:18:02 +05:30

2.3 KiB

<< previous | next >>

Inversion of Control

In the last part you have set up a controller class and generated output with echo. But let's not forget that you have a nice object oriented HTTP abstraction available. But right now it's not accessible inside your class.

The sane option is to use inversion of control. This means that instead of giving the class the responsiblity of creating the object it needs, you just ask for them. This is done with dependency injection.

If it sounds a little complicated right now, don't worry. Just follow the tutorial and once you see how it is implemented things will make more sense.

Change your Homepage controller to the following:

<?php

namespace Example\Controllers;

use Http\Response;

class Homepage
{
    private $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }

    public function show()
    {
        $this->response->setContent('Hello World');
    }
}

Note that you are importing Http\Response at the top of the file. This means that whenever you use Response inside this file, it will resolve to the fully qualified name.

In the constructor you are now explicitly asking for a Http\Response. In this case, Http\Response is an interface. So any class that implements the interface can be injected. See type hinting and interfaces for reference.

Now the code will result in an error because you are not actually injecting anything. So let's fix that in your Bootstrap.php where you dispatch when a route was found:

$class = new $className($response);
$class->$method($vars);

The Http\HttpResponse object implements the Http\Response interface, so it fulfills the contract and can be used.

Now everything should work again. But if you follow this example, all your objects that are instantiated this way will have the same objects injected. This is of course not good, so let's fix that in the next part.

<< previous | next >>