<?php
interface Message
{
public function send();
}
class SendEmail implements Message
{
public function send()
{
echo 'send Email';
}
}
class SendSMS implements Message
{
public function send()
{
echo 'send SMS';
}
}
class Test implements Message
{
public function send()
{
echo 'test';
}
}
class Order
{
protected $message = '';
function __construct(Message $message)
{
$this->message = $message;
}
function sendMsg()
{
$this->message->send();
}
}
class Container
{
protected $binds;
protected $instances;
/**
* @param $abstract 抽象 名称 string
* @param $concrete 具体 实例 object
*/
public function bind($abstract, $concrete)
{
// 如果是匿名函数 闭包 放入binds数组
if ($concrete instanceof Closure) {
$this->binds[$abstract] = $concrete;
} else {
// 实例化对象放入数组
$this->instances[$abstract] = $concrete;
}
}
/**
* 调用
* @param $abstract
* @param array $parameters
* @return mixed
*/
public function make($abstract, $parameters = [])
{
// 存在则返回注册的实例
if (isset($this->instances[$abstract])) {
return $this->instances[$abstract];
}
return call_user_func_array(
$this->binds[$abstract],
$parameters);
}
}
$message = new Container();
$message->bind('SMS', function () {
return new SendSMS();
});
// 闭包 这样的话就是使用的时候才去实例化
$message->bind('EMAIL', function () {
return new SendEmail();
});
// 不使用闭包 这样的化就是 绑定的时候就实例化了
$message->bind('Test', new Test());
$SMS = $message->make('SMS');
$SMS->send();
$Test = $message->make('Test');
$Test->send();
参考 https://www.cnblogs.com/heyue0117/p/11809057.html