dconstructor/dconstructor

dependency injection for lazy p

1.0.0 2017-07-17 17:43 UTC

This package is auto-updated.

Last update: 2024-04-12 21:56:12 UTC


README

Dependency Injection for Lazy People

(all of us btw)

Everybody likes dependency injection (and if it is not your case, you should). However dependency injection sometimes leads us to write of useless code and that, everybody hates.

The purpose of Dconstructor is to free you from certain portions of code which do not serve in much, the happiness of developers as a matter of fact.

Indeed nowadays, we repeat many things, in the properties, in the signature of the constructor, in the body of the constructor. Repeat is null, time to dconstructor KISS

Dconstructor

class UserManager
{
    /**
     * @var Mailer
     */
    private $mailer;

    public function register($email){
        //some code
        $this->mailer->send($email, "Hello !");
    }
}

class Mailer
{
    public function send($recipient, $message)
    {
        //some code
    }
}

Without DI

just take a simple example

class UserManager
{
    public function register($email){
        //some code
        $mailer = new Mailer();
        $mailer->send($email, "Hello !");
    }
}

class Mailer
{
    public function send($recipient, $message)
    {
        //some code
    }
}

Classic DI

class UserManager
{
    /**
     * @var Mailer
     */
    private $mailer;

    public function __construct(Mailer $mailer) {
        $this->mailer = $mailer;
    }

    public function register($email){
        //some code
        $this->mailer->send($email, "Hello !");
    }
}

class Mailer
{
    public function send($recipient, $message)
    {
        //some code
    }
}

Installation

$ composer require dconstructor/dconstructor

Usage

Dconstructor is a simple DI container use it as usual

$container = new Container();

$container->set('foo','bar');

Dconstructor will make injection for you, in our example above for instantiate a new UserManager just call it

$container = new Container();

$userManager = $container->get('UserManager');

Singleton

U can choose to make a class a singleton use annotation for that.

/**
 * @Singleton
 */
class Mailer
{
    //some code
}

$container = new Container();

$mailer = $container->get('Mailer');
$sameMailer = $container->get('Mailer');