MVC结构之Service概念

所有的逻辑都放到M层,M层会臃肿。
所有的逻辑都放到C层,C层会臃肿。
这个时候需要一个中间层,Service层。

Service可以倾向于Model层,比如处理订单查询相关的逻辑。
Service可以倾向于常用的操作,比如计算薪水。或者验证各种邮件等等。
Service也可以介于1,2继续封装出更复杂的功能。

C层调用Service层,能够少写很多代码。

下面是Service的代码。

<?php
/**
 * Created by PhpStorm.
 * User: jiqing
 * Date: 18-12-21
 * Time: 下午8:49
 */

namespace app\common\service;
// 服务层,介于C层与M层之间

/**  根据上面的分析,Service夹在C层和M层中间,从逻辑上大致划分为3大类:
### model侧的Service:也就是封装每个model与业务相关的通用数据接口,比如:查询订单。(我认为:访问远程服务获取数据也应该归属于这一类Service)
### 中间的Service:封装通用的业务逻辑,比如:计算订单折扣(会用到1中的Service)。
### controller侧的Service:基于1、2中的Service进一步封装对外接口的用户业务逻辑。
 **/

use app\common\model\UserModel;

class UserService
{
    public function get_user_info($id) {
        $user = new UserModel();
        return $user->where('id',$id)->find();
    }
}

下面是使用Service的代码。

<?php
namespace app\api\controller;

use app\common\service\UserService;
use func\Http;
use think\Db;
use think\db\Where;

class TestController extends CommonController {

    public function _initialize(){
        parent::_initialize();
    }

    public function test_user() {
        $user_service = new UserService();
        $user_info = $user_service->get_user_info(1);
        halt($user_info);
    }
}

有点意思。这大概就是设计模式吧。灵活的运用命名空间,灵活的创造类。

猜你喜欢

转载自www.cnblogs.com/jiqing9006/p/10158915.html