受不了Backend的curd操作了。重写了部分方法

miwei230 1月前 191

稍微有些操作 appadminlibrarytraitsBackend 中的那些curd方法就不通用了,又得重写。在这里个人重写了类型来继承Backend。重新操作curd

<?php
/**
 * 重写后台管理类
 * 修改部分方法,增加行为钩子
 *@auth bruce·mi
 */
namespace controller;
use app\common\controller\Backend;
class BasicAdmin extends Backend
{
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $param = [
                'where'     => $where,
                'sort'      => $sort,
                'order'     => $order,
                'offset'    => $offset,
                'limit'     => $limit
            ];
            /*参数过滤*/
            if (false === $this->_callback('_param_filter',$param )) {
                    $this->error(__('param filter failure'));
            }
            $list = $this->model
                ->where($param['where'])
                ->order($param['sort'], $param['order'])
                ->limit($param['offset'], $param['limit'])
                ->select();
            $total = $this->model
                ->where($param['where'])
                ->order($param['sort'], $param['order'])
                ->count();
            $list = collection($list)->toArray();
            if (false !== $this->_callback('_data_filter', $list)) {
                $result = array("total" => $total, "rows" => $list);
                return json($result);
            }else{
                $this->error(__('data filter failure'));
            }
        }
        return $this->view->fetch();
    }
    /**
     * 添加|修改
     * @param null $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function save($ids = null){
        $adminIds = $this->getDataLimitAdminIds();
        /*修改*/
        if(!empty($ids)){
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            if($this->request->isGet()){
                $this->view->assign("row", $row);
            }
            if (is_array($adminIds)) {
                if (!in_array($row[$this->dataLimitField], $adminIds)) {
                    $this->error(__('You have no permission'));
                }
            }
        }
        if($this->request->isGet()){
            return $this->view->fetch();
        }
        $params = $this->request->post("row/a");
        if(empty($params)){
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $pk     = $this->model->getPk();
        /*添加*/
        if(empty($ids)){
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $params[$this->dataLimitField] = $this->auth->id;
            }
        }else{
            $params[$pk]    = $ids;
            $this->model->isUpdate(true);
        }
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = basename(str_replace('\\', '/', get_class($this->model)));
                $act  = request()->action();
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.'.$act : true) : $this->modelValidate;
                $this->model->validate($validate);
            }
            /*过滤参数*/
            if (false !== $this->_callback('_save_filter', $params)) {
                $result = $this->model->allowField(true)->save($params);
                if ($result !== false) {
                    if(!$ids) $params[$pk]  = $ids;
                    /*保存成功后,行为钩子*/
                    if (false !== $this->_callback('_save_result', $params)) {
                        $this->success();
                    }else{
                        $this->error(__('save fail!'));
                    }
                } else {
                    $this->error($this->model->getError());
                }
            }
        } catch (\think\exception\PDOException $e) {
            $this->error($e->getMessage());
        }
    }
    /**
     * 添加
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function add()
    {
        return $this->save();
    }
    /**
     * 编辑
     * @param null $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function edit($ids = NULL)
    {
       return $this->save($ids);
    }

    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            //删除前,行为钩子
            if (false === $this->_callback('_delete_filter', $list)) {
                $this->error(__('delete fail!'));
            }
            $count = 0;
            foreach ($list as $k => $v) {
                $count += $v->delete();
            }
            if ($count) {
                //删除后,行为钩子
                if (false !== $this->_callback('_delete_result', $result)) {
                    $this->success();
                }else{
                    $this->error(__('delete fail!'));
                }
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 当前对象回调成员方法
     * @param string $method
     * @param array|bool $data
     * @return bool
     */
    protected function _callback($method, &$data)
    {
        foreach ([$method, "_" . $this->request->action() . "{$method}"] as $_method) {
            if (method_exists($this, $_method) && false === $this->$_method($data)) {
                return false;
            }
        }
        return true;
    }

}

使用,将原来的class Company extends Backend 改成 class Company extends BasicAdmin
然后使用行为钩子,这个以操作edit保存前为例:

 public function _edit_save_filter(&$param){
        $msg = '保存前插入一条消息日志'
        Message::save($param['user_id'],$msg,Message::$pageMap['company_vip']);
    }

写了这么多,只想表达一个意思:
appadminlibrarytraitsBackend 中的方法,灵活度很低。希望Karson大大看到后能后去改进下。

最后于 1月前 被miwei230编辑 (save中缺少where更新条件)
最新回复 (1)
  • fak_all 1月前
    感谢TA
    0 引用 2

    你是这要强ka'r'son的饭碗啊,哈哈哈,牛逼

  • 未登录
    3
返回