PHP code example of hughnoble / injector

1. Go to this page and download the library: Download hughnoble/injector library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hughnoble / injector example snippets


$map = new \Injector\Binding\BindingMap;
$container = \Injector\ContainerFactory::makeContainer($map);

// Any type hinted constructor parameters will be auto-wired.
$class = $container->get(MyClass::class);

class UserRepository
{
    public function __construct(EntityManager $user)
    ...
}

$userRepository = $container->get(UserRepository::class);

$map->add(
    MyInterface::class,
    new Injector\Dependency\AutoWireDependency(MyConcrete::class)
);

$map->add(
    MyInterface::class,
    new Injector\Dependency\ClosureDependency(function($container){
        return new MyConcrete(
            $container->get(ChildInterface::class),
            'something-that-cannot-be-resolved'
        );
    })
);

$childDependency = new Injector\Dependency\ClosureDependency(function($container){
    return new MyConcrete(
        $container->get(ChildInterface::class),
        'something-that-cannot-be-resolved'
    );
});

$map->add(
    MyInterface::class,
    new Injector\Dependency\SingletonBinding($childDependency)
);

$childDependency = new Injector\Dependency\AutoWireDependency(MyClass::class);

$map->add(
    new Injector\Dependency\SingletonDependency(MyClass::class, $childDependency)
);

class UserServiceProvider
{
    private $bindingMap;

    public function __construct(\Injector\Binding\BindingMapInterface $bindingMap)
    {
        $this->bindingMap = $bindingMap;
    }

    public function bindDependencies()
    {
        $this->bindingMap->add(
            UserRepositoryInterface::class,
            new \Injector\Binding\AutoWireBinding(UserRepository::class)
        );
    }
}