pport / ioc
dev-master
2018-03-30 08:43 UTC
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2024-09-22 03:32:54 UTC
README
服务管理器包 pPort : 简单启用应用程序服务、提供者和轻松访问的管理。
安装
使用 composer 安装 pport/ioc
composer require pport/ioc
注册服务提供者
1. 作为一个闭包
<?php
$ioc=new pPort\Ioc\Container();
$student=function($c){
$student_obj=new stdClass();
$student_obj->first_name="Martin";
return $student_obj;
};
$ioc->register('student',$student);
$ioc->student->first_name; //Will output Martin
;?>
2. 作为一个实际类或命名空间
<?php
//or if you have a Student-Class, this will also work with name-spaced classes
class Student
{
public $first_name;
function __construct()
{
$this->first_name='Jones';
}
function get_first_name()
{
return $this->first_name;
}
}
$ioc->register('student_class','Student');
echo $ioc->student->first_name; //Will output Jones
;?>
3. 直接使用 get。
如果没有注册服务,get 将自动注册并返回服务类
$ioc->get('Student');
获取已注册的服务
1. 使用 get 方法
$ioc->get('student');
2. 作为变量调用
$ioc->student;
3. 作为函数调用
$ioc->student();
4. 作为数组参数
$ioc['student'];
依赖项的递归解析
pPort Ioc 支持依赖项的递归解析。下面的 Student 类在加载时将自动注入其依赖项,Teacher 类也将自动注入其依赖项。
<?php
class Lesson
{
public $lesson;
function __construct()
{
$this->lesson='English';
}
function get_class()
{
return $this->lesson;
}
}
class Teacher
{
public $class;
public $lesson;
function __construct(Lesson $lesson)
{
$this->lesson=$lesson;
$this->class='1';
}
function get_class()
{
return $this->class;
}
}
class Student
{
public $teacher;
function __construct(Teacher $teacher)
{
$this->teacher=$teacher;
}
function get_teacher()
{
return $this->teacher;
}
}
//The dependencies are recursively registered and injected to the student class when called
$ioc['Student'];
;?>