PHP code example of anonymous-php / simple-di

1. Go to this page and download the library: Download anonymous-php/simple-di 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/ */

    

anonymous-php / simple-di example snippets




$container = new \Anonymous\SimpleDi\Container([
    'primitive' => 42,
    'wrapped-primitive' => function (\Psr\Container\ContainerInterface $c) {
        return (string)$c->get('primitive');
    },
]);

var_dump($container->get('primitive'), $container->get('wrapped-primitive'));

// int(42)
// string(2) "42"



interface I {}
class A implements I {}
class B implements I {}

$container = new \Anonymous\SimpleDi\Container([
    I::class => A::class,
    B::class => function () {
        return new B();
    },
]);

var_dump(
    $container->instantiate(I::class),
    $container->instantiate(A::class),
    $container->instantiate(B::class, [], I::class)
);

$container->instantiate('C');

/*

object(A)#4 (0) {
}
object(A)#5 (0) {
}
object(B)#7 (0) {
}
PHP Fatal error:  Uncaught Anonymous\SimpleDi\FactoryException Unresolvable dependency 'C'

*/



class A {}

$container = new \Anonymous\SimpleDi\Container();

var_dump(
    $container->instantiate(A::class),
    $container->make(A::class)
);

/*

object(A)#2 (0) {
}
object(A)#2 (0) {
}

*/



class A {
    public function e($v) {
        return $v;
    }
}

class B { 
    public function strtoupper($v) {
        return strtoupper($v);
    }
}

$container = new \Anonymous\SimpleDi\Container();

var_dump(
    $container->injectOn([new A(), 'e'], ['v' => 'value1']),
    $container->injectOn(function (B $b, $v) { return $b->strtoupper($v); }, ['v' => 'value2'])
);

// string(5) "value1"
// string(5) "VALUE2"



interface Filter
{
    public function __invoke($v);
}

class Upper implements Filter
{
    public function __invoke($v)
    {
        return strtoupper($v);
    }
}

interface Output
{
    public function __invoke($v);
}

class StdOutput implements Output
{
    public function __invoke($v)
    {
        echo $v, PHP_EOL;
    }
}

class Printer
{
    protected $filter;

    public function __construct(Filter $filter)
    {
        $this->filter = $filter;
    }

    public function out(Output $output, $value)
    {
        $filter = $this->filter;
        $output($filter instanceof Filter ? $filter($value) : $value);
    }
}

$container = new \Anonymous\SimpleDi\Container([
    Output::class => StdOutput::class,
    Filter::class => Upper::class,
]);

$container->call([Printer::class, 'out'], ['value' => 'Text to print 1']);
$container->call('Printer::out', ['value' => 'Text to print 2']);

// TEXT TO PRINT 1
// TEXT TO PRINT 2

composer