逻辑层
提示
在BaseLogic
中,我们已经定义了几个基础的逻辑层操作方法 add
, edit
, read
, destroy
, search
, getList
, getAll
, getImport
, 通过这些方法,我们可以使得常规的逻辑层变得更简洁,功能更加强大。
逻辑层定义
例如以下控制器中,常规定义只需要做基础定义即可,例如:
php
<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\cms\logic\news;
use plugin\saiadmin\basic\BaseLogic;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\utils\Helper;
use app\cms\model\news\Article;
/**
* 文章管理逻辑层
*/
class ArticleLogic extends BaseLogic
{
/**
* 构造函数
*/
public function __construct()
{
$this->model = new Article();
}
}
逻辑层变异
在逻辑层中,我们通过使用了魔术方法,可以在一定层度上把逻辑层
当作模型层
来使用,变异的逻辑是:如果在logic
中没有找到对应的方法,那么会自动在model
中寻找对应的方法,例如我们在控制器
使用如下代码:
php
<?php
namespace app\cms\controller\news;
use plugin\saiadmin\basic\BaseController;
use app\cms\logic\news\ArticleLogic;
use app\cms\validate\news\ArticleValidate;
use support\Request;
use support\Response;
/**
* 文章管理控制器
*/
class ArticleController extends BaseController
{
/**
* 构造函数
*/
public function __construct()
{
$this->logic = new ArticleLogic();
$this->validate = new ArticleValidate;
parent::__construct();
}
/**
* 批量处理数据
* @param Request $request
* @return Response
*/
public function batchCheck(Request $request) : Response
{
$id = $request->post('id');
// 在logic中没有找到where方法,就会在model中找where方法,这里实际调用的就是model中的where方法
$article = $this->logic->where('id', $id)->findOrEmpty();
// 省略代码
}
}
逻辑层方法重写
在一些特别的情况下,常规逻辑层定义的方法无法满足我们的需求,我们需要对逻辑层
已经定义的方法进行重写,才能实现我们的新功能,例如我们在SystemDeptLogic
这个部门逻辑层中,需要在添加方法中处理parent_id
这个字段的内容,那么常规的add
无法满足我们的需求,我们需要对add
方法进行重写,如下:
php
/**
* 部门逻辑层
*/
class SystemDeptLogic extends BaseLogic
{
/**
* 构造函数
*/
public function __construct()
{
$this->model = new SystemDept();
}
/**
* 添加数据
*/
public function add($data): mixed
{
$data = $this->handleData($data);
$this->model->save($data);
return $this->model->getKey();
}