序言
service是什么?
在面向OO的系統里,service就是biz manager,在面向過程的系統里service就是TS腳本。
service有什么作用?
service層的作用就是把這些需要多個model參與的復雜業務邏輯單獨封裝出來,這些model之間不再發生直接的依賴,而是在service層內協同完成邏輯。service層的第一個目的其實就是對model層進行解耦
需求分析
在Yii2框架中建立service層,專門處理公共且復雜的業務邏輯。
效果
在Yii2 base 項目根目錄創建 service 目錄,所有服務相關的代碼全部放在這個目錄,里面再區分不同模塊
使用方法
Yii::$app->service->appoint->hos($kuid)
//...do something else
實現方法
Service.php
- 文件名:Service.php
- 目錄位置:common/services/Service.php
- 目的:服務層的基類
namespace app\common\services;
use yii\base\BaseObject;
use yii\base\InvalidConfigException;
/**
* 下面這些都是 包含的服務
* @property \app\service\Appoint $appoint
* @property \app\service\Note $note
* @property \app\service\Sms $sms
*/
class Service extends BaseObject
{
public $childService;
public $childServiceList;
/**
* 得到services 里面配置的子服務childService的實例
* @param $childServiceName
* @return Service
* @throws InvalidConfigException
*/
public function getChildService($childServiceName)
{
if (!isset($this->childServiceList[$childServiceName])) {
$childService = $this->childService;
if (isset($childService[$childServiceName])) {
$service = $childService[$childServiceName];
$this->childServiceList[$childServiceName] = \Yii::createObject($service);
} else {
throw new InvalidConfigException(
'Child Service [' . $childServiceName . '] is not find in ' .
get_called_class() . ', you must config it! '
);
}
}
return $this->childServiceList[$childServiceName];
}
/**
*
* @param $attr
* @return object
* @throws InvalidConfigException
*/
public function __get($attr)
{
return $this->getChildService($attr);
}
}
service.php
- 文件名:service.php
- 目錄位置:config/service.php
- 目的:服務配置文件
return [
'appoint' => [ //預約系統相關服務
'class' => 'app\service\Appoint',
'childService' => [
'record' => 'app\service\appoint\Record', //預約系統子服務 記錄相關
]
],
'note' => [
'class' => 'app\service\Note',
],
'sms' => [
'class' => 'app\service\Sms',
],
];
使用方法
使用時,在console.php 或 web.php
$services = require __DIR__ . '/service.php';
$config = [
//....other config
'components' => [
'service' => [
'class' => 'app\common\services\Service',
'childService' => $services
],
//other components