Yii2新增service层

序言

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 appcommonservices;
use yiiaseBaseObject;
use yiiaseInvalidConfigException;
/**
* 下面这些都是 包含的服务
* @property appserviceAppoint $appoint
* @property appserviceNote $note
* @property appserviceSms $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' => 'appserviceAppoint',
        'childService' => [
            'record' => 'appserviceappointRecord', //预约系统子服务 记录相关
        ]
    ],
    'note' => [
        'class' => 'appserviceNote',
    ],
    'sms' => [
        'class' => 'appserviceSms',
    ],
];

使用方法

使用时,在console.php 或 web.php

$services = require __DIR__ . '/service.php';
$config = [
//....other config
    'components' => [
        'service' => [
            'class' => 'appcommonservicesService',
            'childService' => $services
        ],
//other components

源地址:https://www.77xunshan.com/article_details/5

原文地址:https://www.cnblogs.com/meetuj/p/14658666.html