1. Go to this page and download the library: Download dustinfog/canoe-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/ */
dustinfog / canoe-di example snippets
class ClassA
{
}
//DI容器在处理类型时,会在第一次遇到的时候实例化,并且在以后使用中以单例的方式使用。
$a = \Canoe\DI\Context::get(ClassA::class);
class ClassC
{
}
use \Canoe\DI\DITrait;
use \Canoe\DI\Context;
/**
* @property ClassC $c
*/
class ClassA
{
//需要引入一个trait,用以处理$c的获取
use DITrait;
public function test() {
//这里可以直接使用
print_r($this->c);
}
}
$a = Context::get(ClassA::class);
$a->test(); //试一下会发生什么
interface InterfaceC {
public function sayHello();
}
class ClassWorld implements InterfaceC
{
public function sayHello() {
echo "hello, world!\n";
}
}
class ClassC implements InterfaceC
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function sayHello() {
echo "hello, $name!\n";
}
}
use \Canoe\DI\DITrait;
use \Canoe\DI\Context;
/**
* @property InterfaceC $c1 {@uses ClassWorld} //使用类名
* @property InterfaceC $c2 {@uses c2} //使用容器内的ID
*/
class ClassA
{
//需要引入一个trait,用以处理$c的获取
use DITrait;
public function test() {
print_r($this->c1);
print_r($this->c2);
}
}
Context::set("c2", new ClassC("Bob"));
// 更好的选择:Context::registerDefinition("c2", function(){new ClassC("Bob")})
$a = Context::get(ClassA::class);
$a->test(); //试一下会发生什么
use \Canoe\DI\SingletonTrait;
class ClassA
{
use SingletonTrait;
}
$a = ClassA::getInstance();
// 与Context::get(ClassA::class)等价,但隐藏了Context调用。
$a = ClassA::getInstance("a1");
// 与Context::get("a1")等价,但做了进一步的类型检查,即a1取到的实例与ClassA必须有"is a"的关系。
//注册类
Canoe\DI\Context::registerDefinition('a', ClassA::class);
//注册回调
Canoe\DI\Context::registerDefinition(
'b',
function() {
return new ClassB();
}
);
//注册实例
Canoe\DI\Context::set('c', new ClassC());