基础开始示例

demo 地址

基础开发示例已经开源,源码地址:https://github.com/easy-swoole/demo/tree/3.x

安装

框架安装

  • 我们先把当前的 php 环境安装好 swoole 拓展,安装 swoole 扩展 步骤可查看 安装 Swoole 章节,然后执行 php --ri swoole 确保可以看到 swoole 拓展版本为 4.4.23
  • 建立一个目录,名为 Test ,执行 composer require easyswoole/easyswoole=3.4.x 引入 easyswoole
  • 执行 php vendor/bin/easyswoole install 进行安装,然后输入 YY

组件引入

  1. // 引入 IDE 代码提示组件
  2. composer require easyswoole/swoole-ide-helper
  3. // 引入 http-annotation 注解处理组件
  4. composer require easyswoole/http-annotation

命名空间注册

编辑 Test 根目录下的 composer.json 文件,如果自动加载中没有 App 命名空间,请在 autoload.psr-4 中加入 "App\\": "App/",然后执行 composer dumpautoload -o 进行名称空间的更新。composer.json 文件大体结构如下:

  1. {
  2. "require": {
  3. "easyswoole/easyswoole": "3.x",
  4. "easyswoole/swoole-ide-helper": "^1.3",
  5. "easyswoole/http-annotation": "^2.0"
  6. },
  7. "autoload": {
  8. "psr-4": {
  9. "App\\": "App/"
  10. }
  11. }
  12. }

安装后目录结构

  1. Test 项目部署目录
  2. ├─App 应用目录
  3. ├─HttpController 控制器目录(如果没有,请自行创建)
  4. ├─Log 日志文件目录(启动后创建)
  5. ├─Temp 临时文件目录(启动后创建)
  6. ├─vendor 第三方类库目录
  7. ├─bootstrap.php 框架 bootstrap 事件
  8. ├─composer.json Composer 架构
  9. ├─composer.lock Composer 锁定
  10. ├─EasySwooleEvent.php 框架全局事件
  11. ├─easyswoole 框架管理脚本
  12. ├─dev.php 开发配置文件
  13. ├─produce.php 生产配置文件

连接池实现

配置项

我们在 dev.php 配置文件中,加入以下配置信息,注意:请根据自己的 mysql 服务器信息填写账户密码

  1. <?php
  2. return [
  3. // ...... 这里省略
  4. 'MAIN_SERVER' => [
  5. // ...... 这里省略
  6. ],
  7. // ...... 这里省略
  8. // 添加 MySQL 及对应的连接池配置
  9. /*################ MYSQL CONFIG ##################*/
  10. 'MYSQL' => [
  11. 'host' => '127.0.0.1', // 数据库地址
  12. 'port' => 3306, // 数据库端口
  13. 'user' => 'root', // 数据库用户名
  14. 'password' => 'easyswoole', // 数据库用户密码
  15. 'timeout' => 45, // 数据库连接超时时间
  16. 'charset' => 'utf8', // 数据库字符编码
  17. 'database' => 'easyswoole_demo', // 数据库名
  18. 'autoPing' => 5, // 自动 ping 客户端链接的间隔
  19. 'strict_type' => false, // 不开启严格模式
  20. 'fetch_mode' => false,
  21. 'returnCollection' => false, // 设置返回结果为 数组
  22. // 配置 数据库 连接池配置,配置详细说明请看连接池组件 https://www.easyswoole.com/Components/Pool/introduction.html
  23. 'intervalCheckTime' => 15 * 1000, // 设置 连接池定时器执行频率
  24. 'maxIdleTime' => 10, // 设置 连接池对象最大闲置时间 (秒)
  25. 'maxObjectNum' => 20, // 设置 连接池最大数量
  26. 'minObjectNum' => 5, // 设置 连接池最小数量
  27. 'getObjectTimeout' => 3.0, // 设置 获取连接池的超时时间
  28. ],
  29. ];

进行如上配置之后,我们需要在 MySQL 服务端创建一个名为 easyswoole_demo 的数据库,选择字符串编码为 utf8,字符排序规则为 utf8_general_ci

引入数据库 ORM 库

执行以下命令用于实现数据库 ORM 库的引入。

  1. composer require easyswoole/orm=1.4.33

注册数据库连接池

编辑 Test 项目根目录下的 EasySwooleEvent.php 文件,在 mainServerCreate 事件函数中进行 ORM 的连接池的注册,内容如下:

  1. <?php
  2. namespace EasySwoole\EasySwoole;
  3. use EasySwoole\EasySwoole\AbstractInterface\Event;
  4. use EasySwoole\EasySwoole\Swoole\EventRegister;
  5. use EasySwoole\ORM\Db\Connection;
  6. use EasySwoole\ORM\DbManager;
  7. class EasySwooleEvent implements Event
  8. {
  9. public static function initialize()
  10. {
  11. date_default_timezone_set('Asia/Shanghai');
  12. ###### 注册 mysql orm 连接池 ######
  13. $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
  14. // 【可选操作】我们已经在 dev.php 中进行了配置
  15. # $config->setMaxObjectNum(20); // 配置连接池最大数量
  16. DbManager::getInstance()->addConnection(new Connection($config));
  17. }
  18. public static function mainServerCreate(EventRegister $register)
  19. {
  20. }
  21. }

initialize 事件中注册数据库连接池,使用这个 $config 可同时配置连接池大小等。 具体查看 ORM 组件章节 的使用。

模型定义

管理员模型

新增管理员用户表

运行如下 sql 脚本,创建管理员用户表 admin_list

  1. DROP TABLE IF EXISTS `admin_list`;
  2. CREATE TABLE `admin_list` (
  3. `adminId` int(11) NOT NULL AUTO_INCREMENT,
  4. `adminName` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  5. `adminAccount` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  6. `adminPassword` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  7. `adminSession` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  8. `adminLastLoginTime` int(11) NULL DEFAULT NULL,
  9. `adminLastLoginIp` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  10. PRIMARY KEY (`adminId`) USING BTREE,
  11. UNIQUE INDEX `adminAccount`(`adminAccount`) USING BTREE,
  12. INDEX `adminSession`(`adminSession`) USING BTREE
  13. ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;
  14. INSERT INTO `admin_list` VALUES (1, '仙士可', 'xsk', 'e10adc3949ba59abbe56e057f20f883e', '', 1566279458, '192.168.159.1');

新增 model 文件

新建 App/Model/Admin/AdminModel.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\Model\Admin;
  3. use EasySwoole\ORM\AbstractModel;
  4. /**
  5. * Class AdminModel
  6. * @property $adminId
  7. * @property $adminName
  8. * @property $adminAccount
  9. * @property $adminPassword
  10. * @property $adminSession
  11. * @property $adminLastLoginTime
  12. * @property $adminLastLoginIp
  13. */
  14. class AdminModel extends AbstractModel
  15. {
  16. protected $tableName = 'admin_list';
  17. protected $primaryKey = 'adminId';
  18. /**
  19. * @getAll
  20. * @keyword adminName
  21. * @param int page 1
  22. * @param string keyword
  23. * @param int pageSize 10
  24. * @return array[total,list]
  25. */
  26. public function getAll(int $page = 1, string $keyword = null, int $pageSize = 10): array
  27. {
  28. $where = [];
  29. if (!empty($keyword)) {
  30. $where['adminAccount'] = ['%' . $keyword . '%', 'like'];
  31. }
  32. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  33. $total = $this->lastQueryResult()->getTotalCount();
  34. return ['total' => $total, 'list' => $list];
  35. }
  36. /*
  37. * 登录成功后请返回更新后的bean
  38. */
  39. public function login(): ?AdminModel
  40. {
  41. $info = $this->get(['adminAccount' => $this->adminAccount, 'adminPassword' => $this->adminPassword]);
  42. return $info;
  43. }
  44. /*
  45. * 以account进行查询
  46. */
  47. public function accountExist($field = '*'): ?AdminModel
  48. {
  49. $info = $this->field($field)->get(['adminAccount' => $this->adminAccount]);
  50. return $info;
  51. }
  52. public function getOneBySession($field = '*'): ?AdminModel
  53. {
  54. $info = $this->field($field)->get(['adminSession' => $this->adminSession]);
  55. return $info;
  56. }
  57. public function logout()
  58. {
  59. return $this->update(['adminSession' => '']);
  60. }
  61. }

针对上述类似 : ?AdminModel,不懂这种函数返回值类型声明的同学,请查看 函数返回值类型声明,属于 PHP 7 的新特性。

关于 model 的定义可查看 ORM 模型定义章节

关于 IDE 自动提示,只要你在类上面注释中加上 @property $adminIdIDE 就可以自动提示类的这个属性。

普通用户模型

普通用户模型和管理员模型同理。

建表

运行如下 sql 脚本,创建普通用户表 user_list

  1. DROP TABLE IF EXISTS `user_list`;
  2. CREATE TABLE `user_list` (
  3. `userId` int(11) NOT NULL AUTO_INCREMENT,
  4. `userName` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  5. `userAccount` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  6. `userPassword` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  7. `phone` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  8. `addTime` int(11) NULL DEFAULT NULL,
  9. `lastLoginIp` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  10. `lastLoginTime` int(10) NULL DEFAULT NULL,
  11. `userSession` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  12. `state` tinyint(2) NULL DEFAULT NULL,
  13. `money` int(10) NOT NULL DEFAULT 0 COMMENT '用户余额',
  14. `frozenMoney` int(10) NOT NULL DEFAULT 0 COMMENT '冻结余额',
  15. PRIMARY KEY (`userId`) USING BTREE,
  16. UNIQUE INDEX `pk_userAccount`(`userAccount`) USING BTREE,
  17. INDEX `userSession`(`userSession`) USING BTREE
  18. ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;
  19. INSERT INTO `user_list` VALUES (1, '仙士可', 'xsk', 'e10adc3949ba59abbe56e057f20f883e', '', 1566279458, '192.168.159.1', 1566279458, '', 1, 1, 1);

新增 model 文件

新建 App/Model/User/UserModel.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\Model\User;
  3. use EasySwoole\ORM\AbstractModel;
  4. /**
  5. * Class UserModel
  6. * @property $userId
  7. * @property $userName
  8. * @property $userAccount
  9. * @property $userPassword
  10. * @property $phone
  11. * @property $money
  12. * @property $addTime
  13. * @property $lastLoginIp
  14. * @property $lastLoginTime
  15. * @property $userSession
  16. * @property $state
  17. */
  18. class UserModel extends AbstractModel
  19. {
  20. protected $tableName = 'user_list';
  21. protected $primaryKey = 'userId';
  22. const STATE_PROHIBIT = 0; // 禁用状态
  23. const STATE_NORMAL = 1; // 正常状态
  24. /**
  25. * @getAll
  26. * @keyword userName
  27. * @param int page 1
  28. * @param string keyword
  29. * @param int pageSize 10
  30. * @return array[total,list]
  31. */
  32. public function getAll(int $page = 1, string $keyword = null, int $pageSize = 10): array
  33. {
  34. $where = [];
  35. if (!empty($keyword)) {
  36. $where['userAccount'] = ['%' . $keyword . '%', 'like'];
  37. }
  38. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  39. $total = $this->lastQueryResult()->getTotalCount();
  40. return ['total' => $total, 'list' => $list];
  41. }
  42. public function getOneByPhone($field = '*'): ?UserModel
  43. {
  44. $info = $this->field($field)->get(['phone' => $this->phone]);
  45. return $info;
  46. }
  47. /*
  48. * 登录成功后请返回更新后的bean
  49. */
  50. public function login(): ?UserModel
  51. {
  52. $info = $this->get(['userAccount' => $this->userAccount, 'userPassword' => $this->userPassword]);
  53. return $info;
  54. }
  55. public function getOneBySession($field = '*'): ?UserModel
  56. {
  57. $info = $this->field($field)->get(['userSession' => $this->userSession]);
  58. return $info;
  59. }
  60. public function logout()
  61. {
  62. return $this->update(['userSession' => '']);
  63. }
  64. }

banner 模型

建表

运行如下 sql 脚本,创建 bannerbanner_list

  1. DROP TABLE IF EXISTS `banner_list`;
  2. CREATE TABLE `banner_list` (
  3. `bannerId` int(11) NOT NULL AUTO_INCREMENT,
  4. `bannerName` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  5. `bannerImg` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'banner图片',
  6. `bannerDescription` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  7. `bannerUrl` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '跳转地址',
  8. `state` tinyint(3) NULL DEFAULT NULL COMMENT '状态0隐藏 1正常',
  9. PRIMARY KEY (`bannerId`) USING BTREE
  10. ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci;
  11. INSERT INTO `banner_list` VALUES (1, '测试banner', 'asdadsasdasd.jpg', '测试的banner数据', 'www.php20.cn', 1);

新增model文件

新建 App/Model/Admin/BannerModel.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\Model\Admin;
  3. use EasySwoole\ORM\AbstractModel;
  4. /**
  5. * Class BannerModel
  6. * @property $bannerId
  7. * @property $bannerImg
  8. * @property $bannerUrl
  9. * @property $state
  10. */
  11. class BannerModel extends AbstractModel
  12. {
  13. protected $tableName = 'banner_list';
  14. protected $primaryKey = 'bannerId';
  15. public function getAll(int $page = 1, int $state = 1, string $keyword = null, int $pageSize = 10): array
  16. {
  17. $where = [];
  18. if (!empty($keyword)) {
  19. $where['bannerUrl'] = ['%' . $keyword . '%', 'like'];
  20. }
  21. $where['state'] = $state;
  22. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  23. $total = $this->lastQueryResult()->getTotalCount();
  24. return ['total' => $total, 'list' => $list];
  25. }
  26. }

控制器定义

全局基础控制器定义

新建 App/Httpcontroller/BaseController.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\HttpController;
  3. use EasySwoole\EasySwoole\ServerManager;
  4. use EasySwoole\HttpAnnotation\AnnotationController;
  5. class BaseController extends AnnotationController
  6. {
  7. public function index()
  8. {
  9. $this->actionNotFound('index');
  10. }
  11. /**
  12. * 获取用户的真实IP
  13. * @param string $headerName 代理服务器传递的标头名称
  14. * @return string
  15. */
  16. protected function clientRealIP($headerName = 'x-real-ip')
  17. {
  18. $server = ServerManager::getInstance()->getSwooleServer();
  19. $client = $server->getClientInfo($this->request()->getSwooleRequest()->fd);
  20. $clientAddress = $client['remote_ip'];
  21. $xri = $this->request()->getHeader($headerName);
  22. $xff = $this->request()->getHeader('x-forwarded-for');
  23. if ($clientAddress === '127.0.0.1') {
  24. if (!empty($xri)) { // 如果有 xri 则判定为前端有 NGINX 等代理
  25. $clientAddress = $xri[0];
  26. } elseif (!empty($xff)) { // 如果不存在 xri 则继续判断 xff
  27. $list = explode(',', $xff[0]);
  28. if (isset($list[0])) $clientAddress = $list[0];
  29. }
  30. }
  31. return $clientAddress;
  32. }
  33. protected function input($name, $default = null)
  34. {
  35. $value = $this->request()->getRequestParam($name);
  36. return $value ?? $default;
  37. }
  38. }

上述新增的基础控制器 (BaseController.php) 里面的方法用于获取用户 ip,以及获取 api 参数。

上述新增的基础控制器 (BaseController.php) 继承了 \EasySwoole\Http\AbstractInterface\AnnotationController ,这个是注解支持控制器,具体使用可查看 注解章节

api 基础控制器定义

新建 App/Httpcontroller/Api/ApiBase.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\HttpController\Api;
  3. use App\HttpController\BaseController;
  4. use EasySwoole\EasySwoole\Core;
  5. use EasySwoole\EasySwoole\Trigger;
  6. use EasySwoole\Http\Message\Status;
  7. use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
  8. abstract class ApiBase extends BaseController
  9. {
  10. public function index()
  11. {
  12. // TODO: Implement index() method.
  13. $this->actionNotFound('index');
  14. }
  15. protected function actionNotFound(?string $action): void
  16. {
  17. $this->writeJson(Status::CODE_NOT_FOUND);
  18. }
  19. public function onRequest(?string $action): ?bool
  20. {
  21. if (!parent::onRequest($action)) {
  22. return false;
  23. }
  24. return true;
  25. }
  26. protected function onException(\Throwable $throwable): void
  27. {
  28. if ($throwable instanceof ParamValidateError) {
  29. $msg = $throwable->getValidate()->getError()->getErrorRuleMsg();
  30. $this->writeJson(400, null, "{$msg}");
  31. } else {
  32. if (Core::getInstance()->runMode() == 'dev') {
  33. $this->writeJson(500, null, $throwable->getMessage());
  34. } else {
  35. Trigger::getInstance()->throwable($throwable);
  36. $this->writeJson(500, null, '系统内部错误,请稍后重试');
  37. }
  38. }
  39. }
  40. }

上述 api 基类控制器 (ApiBase.php),用于拦截注解异常,以及 api 异常时给用户返回一个 json 格式错误信息。

公共基础控制器定义

新建 App/Httpcontroller/Api/Common/CommonBase.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\HttpController\Api\Common;
  3. use App\HttpController\Api\ApiBase;
  4. class CommonBase extends ApiBase
  5. {
  6. }

公共控制器

公共控制器放不需要登陆即可查看的控制器,例如 banner 列表查看:

新增 App/HttpController/Api/Common/Banner.php 文件,编辑内容如下:

  1. <?php
  2. namespace App\HttpController\Api\Common;
  3. use App\Model\Admin\BannerModel;
  4. use EasySwoole\Http\Message\Status;
  5. use EasySwoole\HttpAnnotation\AnnotationTag\Param;
  6. /**
  7. * Class Banner
  8. */
  9. class Banner extends CommonBase
  10. {
  11. /**
  12. * getOne
  13. * @Param(name="bannerId", alias="主键id", required="", integer="")
  14. * @throws \EasySwoole\ORM\Exception\Exception
  15. * @throws \Throwable
  16. * @author Tioncico
  17. * Time: 14:03
  18. */
  19. public function getOne()
  20. {
  21. $param = $this->request()->getRequestParam();
  22. $model = new BannerModel();
  23. $bean = $model->get($param['bannerId']);
  24. if ($bean) {
  25. $this->writeJson(Status::CODE_OK, $bean, "success");
  26. } else {
  27. $this->writeJson(Status::CODE_BAD_REQUEST, [], 'fail');
  28. }
  29. }
  30. /**
  31. * getAll
  32. * @Param(name="page", alias="页数", optional="", integer="")
  33. * @Param(name="limit", alias="每页总数", optional="", integer="")
  34. * @Param(name="keyword", alias="关键字", optional="", lengthMax="32")
  35. * @throws \EasySwoole\ORM\Exception\Exception
  36. * @author Tioncico
  37. * Time: 14:02
  38. */
  39. public function getAll()
  40. {
  41. $param = $this->request()->getRequestParam();
  42. $page = $param['page'] ?? 1;
  43. $limit = $param['limit'] ?? 20;
  44. $model = new BannerModel();
  45. $data = $model->getAll($page, 1, $param['keyword'] ?? null, $limit);
  46. $this->writeJson(Status::CODE_OK, $data, 'success');
  47. }
  48. }

可以看到,在 getAll 方法中,有着 @Param(name="page", alias="页数", optional="", integer="") 的注释,这个是注解支持写法,可以这样写也不可以不写,当写上这个注释之后,将会约束page 参数必须是 int,具体的验证机制可查看 validate 验证器 章节

使用 php easyswoole server start 命令启动框架服务之后,访问链接:http://127.0.0.1:9501/api/common/banner/getAll (示例访问地址) 即可看到如下结果:{"code":200,"result":{"total":1,"list":[{"bannerId":1,"bannerName":"测试banner","bannerImg":"asdadsasdasd.jpg","bannerDescription":"测试的banner数据","bannerUrl":"www.php20.cn","state":1}]},"msg":"success"} (需要有数据才能看到具体输出)。

管理员基础控制器定义

新建 App/HttpController/Api/Admin/AdminBase.php 文件,编辑内容如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/10/26
  6. * Time: 5:39 PM
  7. */
  8. namespace App\HttpController\Api\Admin;
  9. use App\HttpController\Api\ApiBase;
  10. use App\Model\Admin\AdminModel;
  11. use EasySwoole\Http\Message\Status;
  12. class AdminBase extends ApiBase
  13. {
  14. // public 才会根据协程清除
  15. public $who;
  16. // session 的 cookie头
  17. protected $sessionKey = 'adminSession';
  18. // 白名单
  19. protected $whiteList = [];
  20. /**
  21. * onRequest
  22. * @param null|string $action
  23. * @return bool|null
  24. * @throws \Throwable
  25. * @author yangzhenyu
  26. * Time: 13:49
  27. */
  28. public function onRequest(?string $action): ?bool
  29. {
  30. if (parent::onRequest($action)) {
  31. // 白名单判断
  32. if (in_array($action, $this->whiteList)) {
  33. return true;
  34. }
  35. // 获取登入信息
  36. if (!$this->getWho()) {
  37. $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
  38. return false;
  39. }
  40. return true;
  41. }
  42. return false;
  43. }
  44. /**
  45. * getWho
  46. * @return null|AdminModel
  47. * @author yangzhenyu
  48. * Time: 13:51
  49. */
  50. public function getWho(): ?AdminModel
  51. {
  52. if ($this->who instanceof AdminModel) {
  53. return $this->who;
  54. }
  55. $sessionKey = $this->request()->getRequestParam($this->sessionKey);
  56. if (empty($sessionKey)) {
  57. $sessionKey = $this->request()->getCookieParams($this->sessionKey);
  58. }
  59. if (empty($sessionKey)) {
  60. return null;
  61. }
  62. $adminModel = new AdminModel();
  63. $adminModel->adminSession = $sessionKey;
  64. $this->who = $adminModel->getOneBySession();
  65. return $this->who;
  66. }
  67. }

管理员登录控制器

新建 App/HttpController/Api/Admin/Auth.php 文件,编辑内容如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/10/26
  6. * Time: 5:39 PM
  7. */
  8. namespace App\HttpController\Api\Admin;
  9. use App\Model\Admin\AdminModel;
  10. use EasySwoole\Http\Message\Status;
  11. use EasySwoole\HttpAnnotation\AnnotationTag\Param;
  12. class Auth extends AdminBase
  13. {
  14. protected $whiteList = ['login'];
  15. /**
  16. * login
  17. * 登陆,参数验证注解写法
  18. * @\EasySwoole\HttpAnnotation\AnnotationTag\Param(name="account", alias="帐号", required="", lengthMax="20")
  19. * @Param(name="password", alias="密码", required="", lengthMin="6", lengthMax="16")
  20. * @throws \EasySwoole\ORM\Exception\Exception
  21. * @throws \Throwable
  22. * @author Tioncico
  23. * Time: 10:18
  24. */
  25. public function login()
  26. {
  27. $param = $this->request()->getRequestParam();
  28. $model = new AdminModel();
  29. $model->adminAccount = $param['account'];
  30. $model->adminPassword = md5($param['password']);
  31. if ($user = $model->login()) {
  32. $sessionHash = md5(time() . $user->adminId);
  33. $user->update([
  34. 'adminLastLoginTime' => time(),
  35. 'adminLastLoginIp' => $this->clientRealIP(),
  36. 'adminSession' => $sessionHash
  37. ]);
  38. $rs = $user->toArray();
  39. unset($rs['adminPassword']);
  40. $rs['adminSession'] = $sessionHash;
  41. $this->response()->setCookie('adminSession', $sessionHash, time() + 3600, '/');
  42. $this->writeJson(Status::CODE_OK, $rs);
  43. } else {
  44. $this->writeJson(Status::CODE_BAD_REQUEST, '', '密码错误');
  45. }
  46. }
  47. /**
  48. * logout
  49. * 退出登录,参数注解写法
  50. * @Param(name="adminSession", from={COOKIE}, required="")
  51. * @return bool
  52. * @author Tioncico
  53. * Time: 10:23
  54. */
  55. public function logout()
  56. {
  57. $sessionKey = $this->request()->getRequestParam($this->sessionKey);
  58. if (empty($sessionKey)) {
  59. $sessionKey = $this->request()->getCookieParams('adminSession');
  60. }
  61. if (empty($sessionKey)) {
  62. $this->writeJson(Status::CODE_UNAUTHORIZED, '', '尚未登入');
  63. return false;
  64. }
  65. $result = $this->getWho()->logout();
  66. if ($result) {
  67. $this->writeJson(Status::CODE_OK, '', "登出成功");
  68. } else {
  69. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
  70. }
  71. }
  72. public function getInfo()
  73. {
  74. $this->writeJson(200, $this->getWho()->toArray(), 'success');
  75. }
  76. }

使用 php easyswoole server start 命令启动框架服务之后,访问链接:http://127.0.0.1:9501/Api/Admin/Auth/login?account=xsk&password=123456 (示例访问地址) 即可返回如下结果:``

  1. {
  2. "code": 200,
  3. "result": {
  4. "adminId": 1,
  5. "adminName": "仙士可",
  6. "adminAccount": "xsk",
  7. "adminSession": "b27caf58312d5d4ffc9de42ebf322135",
  8. "adminLastLoginTime": 1615653249,
  9. "adminLastLoginIp": "192.168.65.1"
  10. },
  11. "msg": null
  12. }

管理员用户管理控制器

新增 App/httpController/Api/Admin/User.php 文件,编辑内容如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/10/26
  6. * Time: 5:39 PM
  7. */
  8. namespace App\HttpController\Api\Admin;
  9. use App\Model\User\UserModel;
  10. use EasySwoole\Http\Message\Status;
  11. use EasySwoole\HttpAnnotation\AnnotationTag\Param;
  12. class User extends AdminBase
  13. {
  14. /**
  15. * getAll
  16. * @Param(name="page", alias="页数", optional="", integer="")
  17. * @Param(name="limit", alias="每页总数", optional="", integer="")
  18. * @Param(name="keyword", alias="关键字", optional="", lengthMax="32")
  19. * @author Tioncico
  20. * Time: 14:01
  21. */
  22. function getAll()
  23. {
  24. $page = (int)$this->input('page', 1);
  25. $limit = (int)$this->input('limit', 20);
  26. $model = new UserModel();
  27. $data = $model->getAll($page, $this->input('keyword'), $limit);
  28. $this->writeJson(Status::CODE_OK, $data, 'success');
  29. }
  30. /**
  31. * getOne
  32. * @Param(name="userId", alias="用户id", required="", integer="")
  33. * @throws \EasySwoole\ORM\Exception\Exception
  34. * @throws \Throwable
  35. * @author Tioncico
  36. * Time: 11:48
  37. */
  38. function getOne()
  39. {
  40. $param = $this->request()->getRequestParam();
  41. $model = new UserModel();
  42. $rs = $model->get($param['userId']);
  43. if ($rs) {
  44. $this->writeJson(Status::CODE_OK, $rs, "success");
  45. } else {
  46. $this->writeJson(Status::CODE_BAD_REQUEST, [], 'fail');
  47. }
  48. }
  49. /**
  50. * add
  51. * @Param(name="userName", alias="用户昵称", optional="", lengthMax="32")
  52. * @Param(name="userAccount", alias="用户名", required="", lengthMax="32")
  53. * @Param(name="userPassword", alias="用户密码", required="", lengthMin="6",lengthMax="18")
  54. * @Param(name="phone", alias="手机号码", optional="", lengthMax="18",numeric="")
  55. * @Param(name="state", alias="用户状态", optional="", inArray="{0,1}")
  56. * @author Tioncico
  57. * Time: 11:48
  58. */
  59. function add()
  60. {
  61. $param = $this->request()->getRequestParam();
  62. $model = new UserModel($param);
  63. $model->userPassword = md5($param['userPassword']);
  64. $rs = $model->save();
  65. if ($rs) {
  66. $this->writeJson(Status::CODE_OK, $rs, "success");
  67. } else {
  68. $this->writeJson(Status::CODE_BAD_REQUEST, [], $model->lastQueryResult()->getLastError());
  69. }
  70. }
  71. /**
  72. * update
  73. * @Param(name="userId", alias="用户id", required="", integer="")
  74. * @Param(name="userPassword", alias="会员密码", optional="", lengthMin="6",lengthMax="18")
  75. * @Param(name="userName", alias="会员名", optional="", lengthMax="32")
  76. * @Param(name="state", alias="状态", optional="", inArray="{0,1}")
  77. * @Param(name="phone", alias="手机号", optional="", lengthMax="18")
  78. * @throws \EasySwoole\ORM\Exception\Exception
  79. * @throws \Throwable
  80. * @author Tioncico
  81. * Time: 11:54
  82. */
  83. function update()
  84. {
  85. $model = new UserModel();
  86. /**
  87. * @var $userInfo UserModel
  88. */
  89. $userInfo = $model->get($this->input('userId'));
  90. if (!$userInfo) {
  91. $this->writeJson(Status::CODE_BAD_REQUEST, [], '未找到该会员');
  92. }
  93. $password = $this->input('userPassword');
  94. $update = [
  95. 'userName' => $this->input('userName', $userInfo->userName),
  96. 'userPassword' => $password ? md5($password) : $userInfo->userPassword,
  97. 'state' => $this->input('state', $userInfo->state),
  98. 'phone' => $this->input('phone', $userInfo->phone),
  99. ];
  100. $rs = $model->update($update);
  101. if ($rs) {
  102. $this->writeJson(Status::CODE_OK, $rs, "success");
  103. } else {
  104. $this->writeJson(Status::CODE_BAD_REQUEST, [], $model->lastQueryResult()->getLastError());
  105. }
  106. }
  107. /**
  108. * delete
  109. * @Param(name="userId", alias="用户id", required="", integer="")
  110. * @throws \EasySwoole\ORM\Exception\Exception
  111. * @throws \Throwable
  112. * @author Tioncico
  113. * Time: 14:02
  114. */
  115. function delete()
  116. {
  117. $param = $this->request()->getRequestParam();
  118. $model = new UserModel();
  119. $rs = $model->destroy($param['userId']);
  120. if ($rs) {
  121. $this->writeJson(Status::CODE_OK, $rs, "success");
  122. } else {
  123. $this->writeJson(Status::CODE_BAD_REQUEST, [], '删除失败');
  124. }
  125. }
  126. }

后台管理员登录之后,可通过此文件的接口,去进行会员的增删改查操作 (即 CURD)。

请求地址为:(示例访问地址) http://127.0.0.1:9501/Api/Admin/User/getAll (等方法)

普通用户基础控制器定义

新增 App/HttpController/Api/User/UserBase.php 文件,编辑内容如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/10/26
  6. * Time: 5:39 PM
  7. */
  8. namespace App\HttpController\Api\User;
  9. use App\HttpController\Api\ApiBase;
  10. use App\Model\User\UserModel;
  11. use EasySwoole\Http\Message\Status;
  12. class UserBase extends ApiBase
  13. {
  14. protected $who;
  15. // session 的 cookie 头
  16. protected $sessionKey = 'userSession';
  17. // 白名单
  18. protected $whiteList = ['login', 'register'];
  19. /**
  20. * onRequest
  21. * @param null|string $action
  22. * @return bool|null
  23. * @throws \Throwable
  24. * @author yangzhenyu
  25. * Time: 13:49
  26. */
  27. function onRequest(?string $action): ?bool
  28. {
  29. if (parent::onRequest($action)) {
  30. // 白名单判断
  31. if (in_array($action, $this->whiteList)) {
  32. return true;
  33. }
  34. // 获取登入信息
  35. if (!$data = $this->getWho()) {
  36. $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
  37. return false;
  38. }
  39. // 刷新 cookie 存活
  40. $this->response()->setCookie($this->sessionKey, $data->userSession, time() + 3600, '/');
  41. return true;
  42. }
  43. return false;
  44. }
  45. /**
  46. * getWho
  47. * @author yangzhenyu
  48. * Time: 13:51
  49. */
  50. function getWho(): ?UserModel
  51. {
  52. if ($this->who instanceof UserModel) {
  53. return $this->who;
  54. }
  55. $sessionKey = $this->request()->getRequestParam($this->sessionKey);
  56. if (empty($sessionKey)) {
  57. $sessionKey = $this->request()->getCookieParams($this->sessionKey);
  58. }
  59. if (empty($sessionKey)) {
  60. return null;
  61. }
  62. $userModel = new UserModel();
  63. $userModel->userSession = $sessionKey;
  64. $this->who = $userModel->getOneBySession();
  65. return $this->who;
  66. }
  67. }

普通用户登录控制器

新增 App/HttpController/Api/User/Auth.php 文件,编辑内容如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/10/26
  6. * Time: 5:39 PM
  7. */
  8. namespace App\HttpController\Api\Admin;
  9. use App\Model\Admin\AdminModel;
  10. use EasySwoole\Http\Message\Status;
  11. use EasySwoole\HttpAnnotation\AnnotationTag\Param;
  12. class Auth extends AdminBase
  13. {
  14. protected $whiteList = ['login'];
  15. /**
  16. * login
  17. * 登陆,参数验证注解写法
  18. * @\EasySwoole\HttpAnnotation\AnnotationTag\Param(name="account", alias="帐号", required="", lengthMax="20")
  19. * @Param(name="password", alias="密码", required="", lengthMin="6", lengthMax="16")
  20. * @throws \EasySwoole\ORM\Exception\Exception
  21. * @throws \Throwable
  22. * @author Tioncico
  23. * Time: 10:18
  24. */
  25. public function login()
  26. {
  27. $param = $this->request()->getRequestParam();
  28. $model = new AdminModel();
  29. $model->adminAccount = $param['account'];
  30. $model->adminPassword = md5($param['password']);
  31. if ($user = $model->login()) {
  32. $sessionHash = md5(time() . $user->adminId);
  33. $user->update([
  34. 'adminLastLoginTime' => time(),
  35. 'adminLastLoginIp' => $this->clientRealIP(),
  36. 'adminSession' => $sessionHash
  37. ]);
  38. $rs = $user->toArray();
  39. unset($rs['adminPassword']);
  40. $rs['adminSession'] = $sessionHash;
  41. $this->response()->setCookie('adminSession', $sessionHash, time() + 3600, '/');
  42. $this->writeJson(Status::CODE_OK, $rs);
  43. } else {
  44. $this->writeJson(Status::CODE_BAD_REQUEST, '', '密码错误');
  45. }
  46. }
  47. /**
  48. * logout
  49. * 退出登录,参数注解写法
  50. * @Param(name="adminSession", from={COOKIE}, required="")
  51. * @return bool
  52. * @author Tioncico
  53. * Time: 10:23
  54. */
  55. public function logout()
  56. {
  57. $sessionKey = $this->request()->getRequestParam($this->sessionKey);
  58. if (empty($sessionKey)) {
  59. $sessionKey = $this->request()->getCookieParams('adminSession');
  60. }
  61. if (empty($sessionKey)) {
  62. $this->writeJson(Status::CODE_UNAUTHORIZED, '', '尚未登入');
  63. return false;
  64. }
  65. $result = $this->getWho()->logout();
  66. if ($result) {
  67. $this->writeJson(Status::CODE_OK, '', "登出成功");
  68. } else {
  69. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
  70. }
  71. }
  72. public function getInfo()
  73. {
  74. $this->writeJson(200, $this->getWho()->toArray(), 'success');
  75. }
  76. }

访问 http://127.0.0.1:9501/Api/User/Auth/login?userAccount=xsk&userPassword=123456 即可登录成功。

管理员登录:(示例访问地址) http://127.0.0.1:9501/Api/Admin/Auth/login?account=xsk&password=123456

公共请求 banner:(示例访问地址) http://127.0.0.1:9501/Api/Common/Banner/getAll

会员登录:(示例访问地址) http://127.0.0.1:9501/Api/User/Auth/login?userAccount=xsk&userPassword=123456