Skip to content

Dependency Injection and Services

Durisvk edited this page Dec 18, 2016 · 1 revision

Dependency Injection and Services

If you need to pass an instance (e.g. of a model) to the EOSS class by constructor, you can simply do that with Dependency Injection and Services.

First you need to register a service. Inside app folder create file app/services.eoss which can look something like this:

services: [
    "ExampleModel"
]

We suppose you have already created an ExampleModel. Now what you can do in your xyzEOSS class is this:

<?php
use EOSS\EOSS;

class indexEOSS extends EOSS
{

    public $model;

    public function __construct(ExampleModel $model) {
    	parent::__construct();
        $this->model = $model;
    }

    public function load() {
    	...
    }

    public function bind() {
    	...
    }
}

What now happens is that your ExampleModel will be automatically passed into the constructor and you are well ready to use it.

We can do the same thing using inject* method. The method must be public and must start with keyword inject.

<?php
use EOSS\EOSS;

class indexEOSS extends EOSS
{

    public $model;

    public function injectModel(ExampleModel $model) {
    	$this->model = $model;
    }

    public function load() {
    	...
    }

    public function bind() {
    	...
    }
}

Notice that the class name before argument is required (e.g. ExampleModel $param). Otherwise you get an error.

The last way to inject dependencies and services is not recommended. You can use public property with annotation which will look like this:

use EOSS\EOSS;

class indexEOSS extends EOSS
{
    /**
     * @var ExampleModel @inject
     */
    public $model;

    public function load() { ... }
    public function bind() { ... }
}

This is the most unsecure way to gain dependencies. The @inject anotation is required.

Notice that the instance of the object passed into indexEOSS is always the one and the same. No 2 instances of a same class will be created this way.

PS: I am using Pimple to create this magic.

We are looking for contributors, come and join us, write me an email on durisvk2@gmail.com or post something on a http://eoss.wz.sk .

Clone this wiki locally