DEV Community

Satoshi Nishimura
Satoshi Nishimura

Posted on

Simple Auto Wiring Container

I did not need a DI container but needed auto wiring container.
Originally, I divided the container class I used with my own framework.

GitHub logo nishphp / simple-container

Simple Auto Wiring Container

simple-container

Build Status Coverage Status Code Climate

Latest Stable Version License

Simple container of auto wiring with constructor.

<?php
use Nish\Container\Container
require_once 'vendor/autoload.php'
$c = Container::getInstance()
$obj = $c->get(stdClass::class)
$c->call(Foo::class, 'staticMethod');

$foo = new Foo();
$c->call($foo, 'method');

$c->setFactory('MyClass', function($c){
    return new MyClass('custom param');
});
$c->setFactory(MyClass::class, function($c){
    $obj = new MyClass('custom param');
    $c->set(MyClass::class, $obj); // singleton
    return $obj;
});

// set arguments
namespace MyProject;
class Db {
    private $dsn;
    public function __construct(string $dsn){
        $this->dsn = $dsn;
    }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

This container class has only the basic methods that I actually use in the project.

The implementation of the interface is registered by the set method, and the dependency is written PHP code to the setFactory method.
However, most dependencies will be solved with the Auto Wiring.

class Foo
{
    private $obj;
    public function __construct(stdClass $obj)
    {
        $this->obj = $obj;
    }
}

$c = Container::getInstance();
$foo = $c->get(Foo::class); // constructor injection, no config


// set implements
interface Uri {}
class MyUri implements Uri {}

$c->set(Uri::class, new MyUri);
$uri = $c->get(Uri::class);

// or
$c->setFactory(Uri::class, function($c){
    return new MyUri();
});

// singleton
$c->setFactory(Uri::class, function($c){
    $myUri = new MyUri();
    $c->set(Uri::class, $myUri);
    return $myUri;
});
Enter fullscreen mode Exit fullscreen mode

When using Auto Wiring in a method call, you need to call the call method manually.

class MyIndexAction
{
    public static function index(Request $req, Response $res, MyForm $myForm)
    {
        // ...
    }

    public function __construct(MyForm $myForm) { $this->myForm = $myForm; }
    public function index2(Request $req, Response $res)
    {
        // ...
    }
}

$c->call(MyIndexAction::class, 'index');

// or
$action = $c->get(MyIndexAction::class);
$c->call($action, 'index2');
Enter fullscreen mode Exit fullscreen mode

Most of the functions of this container are explained in these samples.
Simple but when combined with FastRoute, session libraries, etc., a simple micro framework is completed without a moment.

NOTE: I do not know if this program can be used in actual projects. I am trying it.

Top comments (0)