no-framework-tutorial/07-inversion-of-control.md
Madara c20b26c684 Add leading zeros so that files list in correct order
Fix all links to new file names
2015-01-14 15:46:29 +02:00

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\Controller;

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 contructor 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 >>