PHP code example of p810 / ioc-container

1. Go to this page and download the library: Download p810/ioc-container 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/ */

    

p810 / ioc-container example snippets


$container->set(Foo::class);

$instance = new Foo(new Bar);

// this:
$container->set(Foo::class, $factory = null, $instance);

// is the same as this:
$container->singleton(Foo::class, $instance);

// this will trigger a call to ReflectionContainer::resolve() when Foo is requested:
$container->singleton(Foo::class);

// this will invoke the given anonymous function when Foo is requested:
$container->singleton(Foo::class, null, function () use ($bar): Foo {
    return new Foo($bar);
});

// this will invoke the given callback immediately:
$container->singleton(Foo::class, null, function (): Foo {
    return new Foo(new Bar);
}, true);

class Foo {
    /**
     * @param Bar $bar
     * @param Bam $bam
     */
    function __construct(Bar $bar, $bam) {
        $this->bar = $bar;
        $this->bam = $bam;
    }
}

$foo = $container->get(Foo::class);

// this:
$foo = $container->get(Foo::class, [
    'bam' => new Bam,
    'bar' => new Bar
]);

// is the same as this:
$foo = $container->get(Foo::class, new Bar, new Bam);

class Bam {
    function __construct(string $message) {
        $this->message = $message;
    }
}

$entry = $container->set(Bam::class);

$entry->param('message', 'Hello world!');

class Quux {
    function __construct(string $greeting, string $subject) {
        $this->message = \ucfirst($greeting) . ' ' . $subject . '!';
    }
}

$entry = $container->set(Quux::class);

$entry->params([
    'greeting' => 'hello',
    'subject'  => 'world'
]);

interface Baz {
    public function sayHello(string $subject): string;
}

class Bem implements Baz {
    public function sayHello(string $subject): string {
        return "Hello $subject!";
    }
}

$container->bind(Baz::class, Bem::class);

var_dump($container->get(Baz::class) instanceof Bem::class); //=> bool: true