nurse/di

Dependency injection library

v2.1 2016-09-26 14:44 UTC

README

Very simple Dependency Injection Container for PHP

Code information:

Build Status Coverage Status Code Coverage Scrutinizer Code Climate Scrutinizer Code Quality StyleCI

Package information:

Latest Stable Version Total Downloads Latest Unstable Version License Dependency Status

Installing

Installing via Composer

Append the lib to your requirements key in your composer.json.

{
    // composer.json
    // [..]
    require: {
        // append this line to your requirements
        "nurse/di": "dev-master"
    }
}

For PHP 5.3 and 5.4 support use version 0.9.2.

Alternative install

Issues/Features proposals

Here is the issue tracker.

Usage

Defining a dependency:

$container = new Nurse\Container;

// Defining a dependency

$container->set('connection', function ($container) {
    $params = $container->get('connection_params');
    return new Connection($params);
})
->set('connection_params', function () {
    return array(
        'schema'   => 'someschema',
        'username' => 'root',
        'password' => 's3cr3t',
    );
});

// Retrieving the dependency (lazy loading)
$connection = $container->get('connection');

// alternatively you can use the singleton instance of the container

Nurse\Di::set('connection', function ($container) {
    $params = $container->get('connection_params');
    return new Connection($params);
})
->set('connection_params', function () {
    return array(
        'schema'   => 'someschema',
        'username' => 'root',
        'password' => 's3cr3t',
    );
});

$connection = Nurse\Di::get('connection');

You can also create factories:

<?php

namespace App;

use Nurse\Factory\FactoryInterface;
use Nurse\Container;

class ConnectionFactory implements FactoryInterface
{
    public function createService(Container $container)
    {
        $params = $container->get('connection_params');
        return new Connection($params);
    }

    public function getKey()
    {
        return 'connection';
    }
}

And then:

$factory = new \Dummy\MyDummyFactory();
$actual = $container->addFactory($factory);

Contributing

Please refer to the contribuiting guide.

License

MIT

Authors