<?php
//使用依赖注入实现
class Validate{
public function check(){
return '数据验证成功 <br>';
}
}
class Db{
public function connect(){
return '数据库连接成功 <br>';
}
}
class View{
public function display(){
return '用户登录成功 <br>';
}
}
class User{
//创建接收器
protected $db = null;
protected $validate = null;
protected $view = null;
public function login(DB $db,Validate $validate,View $view){
// $db = new Db();
echo $db->connect();
// $validate = new Validate();
echo $validate->check();
// $view = new View();
echo $view->display();
}
}
//客户端实例化
$db = new Db();
$validate = new Validate();
$view = new View();
$user = new User();
echo '<h1>依赖注入实现解耦</h1>';
echo $user->login($db,$validate,$view);
?>
<?php
//使用门面模式
require 'container.php';
class Facade{
protected static $container = null;
public static function initialize(Container $container){
static::$container = $container;
}
public static function connect(){
return static::$container->make('db')->connect();
}
public static function check(){
return static::$container->make('validate')->check();
}
public static function display(){
return static::$container->make('view')->display();
}
}
//客户端调用
Facade::initialize($container);
echo Facade::connect($container);
echo Facade::check($container);
echo Facade::display($container);
?>