Skip to content

Latest commit

 

History

History
62 lines (44 loc) · 1.38 KB

use-dic.md

File metadata and controls

62 lines (44 loc) · 1.38 KB

Use a Dependency Injection Container

This framework will not force you to use a specific Dependency Injection Container. There are a lot of useful DICs out there and you can choose one that you like.

The App object has only two methods that you need:

  • setContainer($container)
  • getContainer()

Here's an example that uses Pimple:

$container = new \Pimple\Container();

$container['someService'] = function () {
    return new SomeService();
};

$router = new \Line\Routing\Router($routes, $errorController);
$app = new \Line\App($router);

// set the container to make it available in all Controllers
$app->setContainer($container);

$app->run();

In the Controller you can now get the Container to access the services.

public function someAction(App $app)
{
    $someService = $app->getContainer()['someService'];
}

Extend the App to autocomple services.

If you want to use autocompletion in your IDE, you can extend the App class.

/**
 * @property SomeService $someService
 */
class MyApp extends \Line\App
{
    public function __get($name)
    {
        return $this->getContainer()[$name];
    }
}

Because of the magic __get() method and the @property comment you can now use the autocompletion if your IDE supports it:

Autocomplete


Back to overview