PHP code example of wazsmwazsm / ioc-container

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

    

wazsmwazsm / ioc-container example snippets


use IOC\Container;

class Foo
{
    public $a = 1;
    public $b = 2;
}

class Foz
{
    public $a = 5;
    public $b = 6;
    public function __construct(Foo $foo)
    {
        $this->a = $foo->a + $this->a;
        $this->b = $foo->b + $this->b;
    }
}

class Bar
{
    public $a = 0;
    public $b = 0;
    public function __construct(Foz $foz)
    {
        $this->a = $foz->a;
        $this->b = $foz->b;
    }
}

// 获取 Bar 的实例,Container 会自动进行依赖注入
$bar = Container::getInstance(Bar::class);
var_dump($bar->a); // 6
var_dump($bar->b); // 8

Container::getInstance(Bar::class, ['param1', 'param2']);

use IOC\Container;

class Foo
{
    public $a = 1;
    public $b = 2;
}

class Bar
{
    public function f1(Foo $foo)
    {
        return $foo->a + $foo->b;
    }
}

$result = Container::run(Bar::class, 'f1'); // result is 3

use IOC\Container;

class Foo
{
    public $a = 1;
    public $b = 2;
}

class Bar
{
	// 注意额外传入的参数应该在要注入的参数之后
    public function f1(Foo $foo, $c, $d)
    {
        return $foo->a + $foo->b + $c + $d;
    }
}

$result = Container::run(Bar::class, 'f1', [4, 2]); // result is 9

Container::run(Bar::class, 'f1', [4, 2], ['param1', 'param2']);

use IOC\Container;
...
$a = new A();

Container::singleton($a);

use IOC\Container;

// 传入要获取单例的类名
$a = Container::getSingleton('A');

use IOC\Container;

$a = new A();
// 设置单例,指定名称
Container::singleton($a, 'my_singleton');
// 获取单例
$a = Container::getSingleton('my_singleton');

use IOC\Container;

// 销毁类 A 的单例
Container::unsetSingleton('A');
// 再次获取为 null
Container::getSingleton('A');

use IOC\Container;

// set exception handler
Container::register(
    Exceptions\ExceptionHandler::class, 
    App\Exceptions\Handler::class
);

// get singleton 这里获取的其实是 App\Exceptions\Handler 的实例
$handler = Container::getSingleton(Exceptions\ExceptionHandler::class);


use IOC\Container;

// set exception handler
Container::register(Exceptions\ExceptionHandler::class);

// get singleton 这里获取的是 Exceptions\ExceptionHandler 的实例
$handler = Container::getSingleton(Exceptions\ExceptionHandler::class);