g4 dependencies injection container based on Pimple

1.0.1 2018-03-08 11:35 UTC


DI - dependencies injection container - singleton Pimple wrapper https://github.com/silexphp/Pimple

  • easy access by a method not by an array property
  • no need to remember DI array keys (or go back to the DI class to look) every time you need something
  • type hinting


Using Composer and Packagist https://packagist.org/packages/g4/di

composer require g4/di


Services are defined by anonymous functions that returns an instance of an object. Define all services in one DI Container class inside your application:

namespace MyNamespace;

use G4\DI\Container;

class DI extends Container
     * @return \MyNamespace\MyConfig
    public static function configInstance()
        return self::registerShare(function (DI $c) {
            return new \MyNamespace\MyConfig();
     * @return \MyNamespace\MyClass
    public static function myClassInstance()
        return self::registerFactory(function (DI $c) {
            return new \MyNamespace\MyClass($c::configInstance());


  • registerFactory($callable) - Register a service that will each time return new instance of it
  • registerShare($callable) - Register a service that will each time return the same instance of it

Using the defined services

use MyNamespace\DI;

$myClass = DI::myClassInstance();

// the above call is equivalent to:
// $myConfig = new \MyNamespace\MyConfig();
// $myClass = new \MyNamespace\MyClass($myConfig);


Install dependencies

$ make install

Run tests

$ make test


(The MIT License) see LICENSE file for details...