gquental / cakephp-service-container

CakePHP 服务容器

0.0.8 2014-02-15 00:59 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:06:31 UTC


README

本项目旨在为 CakePHP 框架提供服务容器功能和依赖注入功能。

##安装

为了安装它,有两种选择:通过 composer 安装或手动安装。

###composer

您只需在您的 composer.json 文件中添加 gquental/cakephp-service-container 包,然后运行安装命令。完成此过程后,会在您的 CakePHP 插件文件夹内创建一个名为 ServiceContainer 的文件夹。

###手动安装

只需在您的 CakePHP 插件文件夹内克隆项目,并将目录命名为 ServiceContainer

##使用方法

###配置文件

在插件正确安装后,第一步是创建配置文件,然后在 CakePHP 配置引导文件 (app/Config/bootstrap.php) 中注册它。

例如,如果您将文件命名为 services.php,您需要在引导文件中写入以下行:

// First parameter is the name of the file without the extension
// The second parameter is the name of the configuration reader,
// which in CakePHP the default is the PHP file reader
Configure::load('services', 'default');

####配置文件示例

$config = array(
	'Services' => array(
		'ServiceName' => array(
			'name' => 'name of the class',
			'path' => 'path of the class'
			'arguments' => [1, 2, 3]
		)
	)
);

###使用 ServiceContainer 组件

为了调用容器内的服务,您需要使用插件提供的 CakePHP 组件。为了这样做,您需要在 components 数组中添加以下条目。

$components = ['ServiceContainer.ServiceContainer'];

组件准备就绪后,您可以通过调用 getService 方法来调用一个服务。

public function actionX() {
	$service = $this->ServiceContainer->getService('serviceName');
}

###依赖注入

假设在我们的容器中有两个类,User 和 Contact 类。Contact 类需要一个用户实例和一个整数,表示它应该拥有的最大电话数量。

我们可以通过服务容器而不是在 Contact 类中手动实例化来传递所有这些依赖项。为此,我们需要在服务容器配置文件中传递参数给 Contact 类。

在参数中,我们可以传递原始值或配置文件中已存在的另一个服务,只需传递一个以 @ 开头的服务名称字符串即可,例如对于 User 类:"@User"

以下是如何创建这种情况的示例

app/Config/services.php

$config = array(
	'Services' => array(
		'User' => array(
			'name' => 'UserEntity',
			'path' => 'Lib'
		),
		'Contact' => array(
			'name' => 'ContactEntity',
			'path' => 'Lib',
			'arguments' => ['@User', 3]
		)
	)
);

someController.php

public function action() {
	$contact = $this->ServiceContainer->get('Contact');
}

Lib/UserEntity.php

class UserEntity {}

Lib/ContactEntity.php

class ContactEntity {
	public $user;
	public $maxPhones;
	
	public function __construct($user, $maxPhones) {
		$this->user = $user;
		$this->maxPhones = $maxPhones;
	}
}