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
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