[BD] 框架源码研究之新增用户

77 阅读1分钟

代码位置

app\admin\controller\auth\Admin.php

添加用户代码

public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            /**
             * 由于有密码字段-对方法进行重写
             * 数据验证
             */
            if ($this->modelValidate) {
                try {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = new $validate;
                    $validate->scene('add')->check($data);
                } catch (ValidateException $e) {
                    $this->error($e->getMessage());
                }
            }

            $salt   = Random::build('alnum', 16);
            $passwd = encrypt_password($data['password'], $salt);

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                $data['salt']     = $salt;
                $data['password'] = $passwd;
                
                /**
                 * array:7 [
                 *  "status" => "1"
                 *  "username" => "zhangsan"
                 *  "nickname" => "张三"
                 *  "group_arr" => array:1 [
                 *      0 => "3"
                 *   ]
                 *   "mobile" => "13800138000"
                 *   "salt" => "RpUoGcwnvTl68myO"
                 *   "password" => "32488ff98fcdae4d3a125490d1c81146"
                 *  ]
                 */
                $result           = $this->model->save($data); // 1.添加用户
                if ($data['group_arr']) {
                    $groupAccess = [];
                    foreach ($data['group_arr'] as $datum) {
                        $groupAccess[] = [
                            'uid'      => $this->model->id,
                            'group_id' => $datum,
                        ];
                    }
                    /**
                     * array:1 [
                     *    0 => array:2 [
                     *         "uid" => 6
                     *          "group_id" => "3"
                     *     ]
                     *  ]
                     */
                    Db::name('admin_group_access')->insertAll($groupAccess); // 2.添加用户权限关联
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }