本文主要是介绍最新Swoole实战之手撸HttpServer框架课程笔记依赖注入/控制反转代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<?php
require_once dirname(dirname(__FILE__)) . "/vendor/autoload.php";class MyDB
{private $db;//这里可能是pdo 可能是别的,仅仅为了演示public function __construct($connInfo){//略}public function queryForRows($sql){return ['user_id' => 101, "user_name" => "shenyi"];}
}class MyUser
{//老大private $mydb;public function __construct(MyDB $DB){$this->mydb = $DB;//$this->mydb=new MyDB($dsn);//主动实例化DB}public function getAllUsers(): array{//业务方法return $this->mydb->queryForRows("select * from users");}
}//IOC容器原理
class ClassFactory
{private static $container = [];public static function set(string $name, callable $func){self::$container[$name] = $func;}public static function get($name){if (isset(self::$container[$name])) {return self::$container[$name];}return null;}
}$container = new DI\Container();
$container->set("mydb", function () {return new MyDB("xxxoo");
});
$container->set("myuser", function (\DI\Container $c) {return new MyUser($c->get("mydb"));
});
$myuser = $container->get("myuser");
var_dump($myuser->getAllUsers());
这篇关于最新Swoole实战之手撸HttpServer框架课程笔记依赖注入/控制反转代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!