- 默认方法
- 默认方法
- 复杂实例
默认方法
默认方法
默认由 IOC 容器托管的对象都会被添加上两个方法;
| 方法 | 含义 |
|---|---|
| _initialize | 初始化方法 |
| _prepared | 初始化完成方法 |
_initialize::可以注入多个任意你需要的对象
实例:
class UserService{/*** @var Connection*/private $connection;public function _initialize(Connection $connection) {$this->connection = $connection;}public function _prepared(){if($this->connection){//这里connection 已有值}}}
复杂实例
下面的实例正式项目不一定能遇到,但是这里可以看出 AService,BService的相互依赖关系和如何进行AService,BService的充分解耦这里为了方便没有使用接口
class AService{/*** @var BService*/private $bService;public function _initialize(BService $bService){$this->bService=$bService;}public function test(){$this->bService->write();}public function xxx(){echo 'AService的 xxx 方法被调用';}}class BService{/*** @var AService*/private $aService;public function _initialize(AService $aService){$htis->aService=$AService;}public function write(){echo 'BService write 方法被调用';$this->aService->xxx();}}//使用function test(){$a=Ioc::get(AService::class);$a->test();}
有兴趣的可以试下
思考1: 如果不在 IOC 容器内如何实现写上面的实例(只能有两个对象哦 别出现 A 每次都 new 哦)思考2: 为什么有 _prepared 方法
上一篇:容器使用 下一篇:Facade(门面模式)
