<?php
class Container
{
protected $binds;
protected $instances;
public function bind($abstract, $concrete)
{
if($concrete instanceof Closure) {
$this->binds[$abstract] = $concrete;
} else {
$this->instances[$abstract] = $concrete;
}
}
public function make($abstract, $parameters=[]){
if (isset($this->instances[$abstract])){
return $this->instances[$abstract];
}
array_unshift($parameters, $this);
return call_user_func_array($this->binds[$abstract], $parameters);
}
}
interface Phone {
public function openApp(string $name);
}
class iPhone implements Phone {
public function openApp(string $name){
echo __CLASS__ . " run app " . $name . PHP_EOL;
}
}
class XiaoMi8 implements Phone {
public function openApp(string $name) {
echo __CLASS__ . " run app " . $name . PHP_EOL;
}
}
class People
{
public function run (Phone $phone, $name){
$phone->openApp($name);
}
}
$xiaomi_8 = function () {
return new XiaoMi8();
};
$iphone = function () {
return new iPhone();
};
$pepole = function () {
return new People();
};
$app = new Container();
$app->bind(iPhone::class, function() { return new iPhone(); });
$app->bind(XiaoMi8::class, function() { return new XiaoMi8(); });
//$app->bind(People::class, function() { return new People(); });
$app->bind(People::class, new People());
(new People)->run(new XiaoMi8(), 'DonYin');
(new People)->run(new iPhone(), 'WeChat');
$pepole_01 = $app->make(People::class);
$pepole_01->run($app->make(XiaoMi8::class), 'DingTalk');
$pepole_01->run($app->make(iPhone::class), 'DingTalk');
$pepole_01->run($app->make(iPhone::class), 'Baidu Map');
$pepole_02 = $app->make(People::class);
var_dump($pepole_01);
var_dump($pepole_02);
var_dump($pepole_01 === $pepole_02);
var_dump($pepole_01 == $pepole_02);