title: Easyswoole基础开发示例 meta:

  • name: description content: EasySwoole基础开发示例,手把手教你怎么用easyswoole实现一个api接口网站
  • name: keywords content: swoole|swoole 拓展|swoole 框架|easyswoole|swoole 扩展|swoole框架|swoole开发示例|swoole

基础开发示例

demo地址

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

安装

框架安装

  • 我们先安装好swooole拓展,执行 php --ri swoole 确保可以看到swoole拓展最版本为4.4.8
  • 建立一个目录,名为 Test ,执行 composer require easyswoole/easyswoole=3.x 引入easyswoole
  • 执行php vendor/bin/easyswoole install 进行安装

命名空间注册

编辑Test根目录下的 composer.json 文件,加入"App\\": "App/" ,大体结构如下:

  1. {
  2. "autoload": {
  3. "psr-4": {
  4. "App\\": "App/"
  5. }
  6. },
  7. "require": {
  8. "easyswoole/easyswoole": "3.x"
  9. }
  10. }

安装后目录结构

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

执行以下命令进行名称空间的更新:

  1. composer dumpautoload

连接池实现

配置项

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

  1. 'MYSQL' => [
  2. 'host' => '',
  3. 'port' => 3300,
  4. 'user' => '',
  5. 'password' => '',
  6. 'database' => '',
  7. 'timeout' => 5,
  8. 'charset' => 'utf8mb4',
  9. ]

引入ORM库

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

  1. composer require easyswoole/orm

事件注册

我们编辑根目录下的EasySwooleEvent.php文件,在mainServerCreate事件中进行ORM的连接注册,大体结构如下:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2018/5/28
  6. * Time: 下午6:33
  7. */
  8. namespace EasySwoole\EasySwoole;
  9. use EasySwoole\EasySwoole\Swoole\EventRegister;
  10. use EasySwoole\EasySwoole\AbstractInterface\Event;
  11. use EasySwoole\Http\Request;
  12. use EasySwoole\Http\Response;
  13. use EasySwoole\ORM\Db\Connection;
  14. use EasySwoole\ORM\DbManager;
  15. class EasySwooleEvent implements Event
  16. {
  17. public static function initialize()
  18. {
  19. date_default_timezone_set('Asia/Shanghai');
  20. }
  21. public static function mainServerCreate(EventRegister $register)
  22. {
  23. $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
  24. DbManager::getInstance()->addConnection(new Connection($config));
  25. }
  26. public static function onRequest(Request $request, Response $response): bool
  27. {
  28. // TODO: Implement onRequest() method.
  29. return true;
  30. }
  31. public static function afterRequest(Request $request, Response $response): void
  32. {
  33. // TODO: Implement afterAction() method.
  34. }
  35. }

::: warning 在initialize事件中注册数据库连接池,这个$config可同时配置连接池大小等 :::

模型定义

管理员模型

新增管理员用户表:

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

::: warning model的定义可查看orm章节 ::: ::: warning 关于ide自动提示,只要你在类上面注释中加上@property $adminId ide就可以自动提示类的这个属性 :::

普通用户模型

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

建表

  1. CREATE TABLE if not exists `user_list` (
  2. `userId` int(11) NOT NULL AUTO_INCREMENT,
  3. `userName` varchar(32) NOT NULL,
  4. `userAccount` varchar(18) NOT NULL,
  5. `userPassword` varchar(32) NOT NULL,
  6. `phone` varchar(18) NOT NULL,
  7. `addTime` int(11) DEFAULT NULL,
  8. `lastLoginIp` varchar(20) DEFAULT NULL,
  9. `lastLoginTime` int(10) DEFAULT NULL,
  10. `userSession` varchar(32) DEFAULT NULL,
  11. `state` tinyint(2) DEFAULT NULL,
  12. `money` int(10) NOT NULL DEFAULT '0' COMMENT '用户余额',
  13. `frozenMoney` int(10) NOT NULL DEFAULT '0' COMMENT '冻结余额',
  14. PRIMARY KEY (`userId`),
  15. UNIQUE KEY `pk_userAccount` (`userAccount`),
  16. KEY `userSession` (`userSession`)
  17. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  18. 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. * Create With Automatic Generator
  7. * @property $userId
  8. * @property $userName
  9. * @property $userAccount
  10. * @property $userPassword
  11. * @property $phone
  12. * @property $money
  13. * @property $addTime
  14. * @property $lastLoginIp
  15. * @property $lastLoginTime
  16. * @property $userSession
  17. * @property $state
  18. */
  19. class UserModel extends AbstractModel
  20. {
  21. protected $tableName = 'user_list';
  22. protected $primaryKey = 'userId';
  23. const STATE_PROHIBIT = 0; // 禁用状态
  24. const STATE_NORMAL = 1; // 正常状态
  25. /**
  26. * @getAll
  27. * @keyword userName
  28. * @param int page 1
  29. * @param string keyword
  30. * @param int pageSize 10
  31. * @return array[total,list]
  32. */
  33. public function getAll(int $page = 1, string $keyword = null, int $pageSize = 10): array
  34. {
  35. $where = [];
  36. if (!empty($keyword))
  37. {
  38. $where['userAccount'] = ['%' . $keyword . '%','like'];
  39. }
  40. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  41. $total = $this->lastQueryResult()->getTotalCount();
  42. return ['total' => $total, 'list' => $list];
  43. }
  44. public function getOneByPhone($field = '*'): ?UserModel
  45. {
  46. $info = $this->field($field)->get(['phone' => $this->phone]);
  47. return $info;
  48. }
  49. /*
  50. * 登录成功后请返回更新后的bean
  51. */
  52. public function login():?UserModel
  53. {
  54. $info = $this->get(['userAccount' => $this->userAccount,'userPassword' => $this->userPassword]);
  55. return $info;
  56. }
  57. public function getOneBySession($field = '*'):?UserModel
  58. {
  59. $info = $this->field($field)->get(['userSession' => $this->userSession]);
  60. return $info;
  61. }
  62. public function logout()
  63. {
  64. return $this->update(['userSession' => '']);
  65. }
  66. }

banner模型

建表

  1. CREATE TABLE if not exists `banner_list` (
  2. `bannerId` int(11) NOT NULL AUTO_INCREMENT,
  3. `bannerName` varchar(32) DEFAULT NULL,
  4. `bannerImg` varchar(255) NOT NULL COMMENT 'banner图片',
  5. `bannerDescription` varchar(255) DEFAULT NULL,
  6. `bannerUrl` varchar(255) DEFAULT NULL COMMENT '跳转地址',
  7. `state` tinyint(3) DEFAULT NULL COMMENT '状态0隐藏 1正常',
  8. PRIMARY KEY (`bannerId`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  10. 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. * Create With Automatic Generator
  7. * @property $bannerId
  8. * @property $bannerImg
  9. * @property $bannerUrl
  10. * @property $state
  11. */
  12. class BannerModel extends AbstractModel
  13. {
  14. protected $tableName = 'banner_list';
  15. protected $primaryKey = 'bannerId';
  16. public function getAll(int $page = 1,int $state=1, string $keyword = null, int $pageSize = 10): array
  17. {
  18. $where = [];
  19. if (!empty($keyword)) {
  20. $where['bannerUrl'] = ['%' . $keyword . '%','like'];
  21. }
  22. $where['state'] = $state;
  23. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  24. $total = $this->lastQueryResult()->getTotalCount();
  25. return ['total' => $total, 'list' => $list];
  26. }
  27. }

控制器定义

全局基础控制器定义

新增 App/Httpcontroller/BaseController 文件:

  1. <?php
  2. namespace App\HttpController;
  3. use EasySwoole\EasySwoole\ServerManager;
  4. use EasySwoole\Http\AbstractInterface\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. {
  25. if (!empty($xri))
  26. { // 如果有xri 则判定为前端有NGINX等代理
  27. $clientAddress = $xri[0];
  28. }
  29. elseif (!empty($xff))
  30. { // 如果不存在xri 则继续判断xff
  31. $list = explode(',', $xff[0]);
  32. if (isset($list[0])) $clientAddress = $list[0];
  33. }
  34. }
  35. return $clientAddress;
  36. }
  37. protected function input($name, $default = null)
  38. {
  39. $value = $this->request()->getRequestParam($name);
  40. return $value ?? $default;
  41. }
  42. }

::: warning 新增基础控制器,里面的方法用于获取用户ip,以及获取api参数
:::

::: warning 基础控制器继承了EasySwoole\Http\AbstractInterface\AnnotationController,这个是注解支持控制器,可查看注解章节 :::

api基础控制器定义

新增 App/Httpcontroller/Api/ApiBase.php 文件:

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

::: warning api基类控制器,用于拦截注解异常,以及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\BannerBean;
  4. use App\Model\Admin\BannerModel;
  5. use EasySwoole\Http\Annotation\Param;
  6. use EasySwoole\Http\Message\Status;
  7. use EasySwoole\MysqliPool\Mysql;
  8. use EasySwoole\Validate\Validate;
  9. /**
  10. * Class Banner
  11. * Create With Automatic Generator
  12. */
  13. class Banner extends CommonBase
  14. {
  15. /**
  16. * getOne
  17. * @Param(name="bannerId", alias="主键id", required="", integer="")
  18. * @throws \EasySwoole\ORM\Exception\Exception
  19. * @throws \Throwable
  20. * @author Tioncico
  21. * Time: 14:03
  22. */
  23. public function getOne()
  24. {
  25. $param = $this->request()->getRequestParam();
  26. $model = new BannerModel();
  27. $model->bannerId = $param['bannerId'];
  28. $bean = $model->get();
  29. if ($bean) {
  30. $this->writeJson(Status::CODE_OK, $bean, "success");
  31. } else {
  32. $this->writeJson(Status::CODE_BAD_REQUEST, [], 'fail');
  33. }
  34. }
  35. /**
  36. * getAll
  37. * @Param(name="page", alias="页数", optional="", integer="")
  38. * @Param(name="limit", alias="每页总数", optional="", integer="")
  39. * @Param(name="keyword", alias="关键字", optional="", lengthMax="32")
  40. * @author Tioncico
  41. * Time: 14:02
  42. */
  43. public function getAll()
  44. {
  45. $param = $this->request()->getRequestParam();
  46. $page = $param['page'] ?? 1;
  47. $limit = $param['limit'] ?? 20;
  48. $model = new BannerModel();
  49. $data = $model->getAll($page, 1, $param['keyword']??null, $limit);
  50. $this->writeJson(Status::CODE_OK, $data, 'success');
  51. }
  52. }

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

::: warning 测试链接:127.0.0.1:9501/api/common/banner/getAll :::

::: warning 需要有数据才能看到具体输出 :::

管理员基础控制器定义

新增 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\Annotation\Param;
  11. use EasySwoole\Http\Message\Status;
  12. class Auth extends AdminBase
  13. {
  14. protected $whiteList=['login'];
  15. /**
  16. * login
  17. * 登陆,参数验证注解写法
  18. * @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. }

::: warning 可看到,在getAll方法中,有着@Param(name="account", alias="帐号", required="", lengthMax="20")的注释,这个是注解支持写法,可写也不可以不写,当写上这个注释之后,将会约束page参数必须是int,具体的验证机制可查看validate验证器 :::

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

::: warning 后台管理员登陆之后,可通过此文件的接口,去进行curd会员
:::

::: warning 请求地址为: 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\UserBean;
  11. use App\Model\User\UserModel;
  12. use App\Utility\Pool\RedisPool;
  13. use EasySwoole\Http\Message\Status;
  14. use EasySwoole\MysqliPool\Mysql;
  15. use EasySwoole\Spl\SplBean;
  16. use EasySwoole\Validate\Validate;
  17. class UserBase extends ApiBase
  18. {
  19. protected $who;
  20. //session的cookie头
  21. protected $sessionKey = 'userSession';
  22. //白名单
  23. protected $whiteList = ['login', 'register'];
  24. /**
  25. * onRequest
  26. * @param null|string $action
  27. * @return bool|null
  28. * @throws \Throwable
  29. * @author yangzhenyu
  30. * Time: 13:49
  31. */
  32. public function onRequest(?string $action): ?bool
  33. {
  34. if (parent::onRequest($action)) {
  35. //白名单判断
  36. if (in_array($action, $this->whiteList)) {
  37. return true;
  38. }
  39. //获取登入信息
  40. if (!$data = $this->getWho()) {
  41. $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
  42. return false;
  43. }
  44. //刷新cookie存活
  45. $this->response()->setCookie($this->sessionKey, $data->getUserSession(), time() + 3600, '/');
  46. return true;
  47. }
  48. return false;
  49. }
  50. /**
  51. * getWho
  52. * @author yangzhenyu
  53. * Time: 13:51
  54. */
  55. public function getWho(): ?UserModel
  56. {
  57. if ($this->who instanceof UserModel) {
  58. return $this->who;
  59. }
  60. $sessionKey = $this->request()->getRequestParam($this->sessionKey);
  61. if (empty($sessionKey)) {
  62. $sessionKey = $this->request()->getCookieParams($this->sessionKey);
  63. }
  64. if (empty($sessionKey)) {
  65. return null;
  66. }
  67. $userModel = new UserModel();
  68. $userModel->userSession = $sessionKey;
  69. $this->who = $userModel->getOneBySession();
  70. return $this->who;
  71. }
  72. }

普通用户登录控制器

新增 App/HttpController/Api/User/Auth.php文件:

  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yf
  5. * Date: 2019-04-02
  6. * Time: 13:03
  7. */
  8. namespace App\HttpController\Api\User;
  9. use App\Model\User\UserBean;
  10. use App\Model\User\UserModel;
  11. use App\Service\Common\VerifyService;
  12. use App\Utility\SwooleApi\User\Login;
  13. use EasySwoole\Http\Annotation\Param;
  14. use EasySwoole\Http\Message\Status;
  15. use EasySwoole\MysqliPool\Mysql;
  16. use EasySwoole\Spl\SplBean;
  17. use EasySwoole\Validate\Validate;
  18. class Auth extends UserBase
  19. {
  20. protected $whiteList = ['login', 'register'];
  21. /**
  22. * login
  23. * @Param(name="userAccount", alias="用户名", required="", lengthMax="32")
  24. * @Param(name="userPassword", alias="密码", required="", lengthMin="6",lengthMax="18")
  25. * @throws \EasySwoole\ORM\Exception\Exception
  26. * @throws \Throwable
  27. * @author Tioncico
  28. * Time: 15:06
  29. */
  30. public function login()
  31. {
  32. $param = $this->request()->getRequestParam();
  33. $model = new UserModel();
  34. $model->userAccount = $param['userAccount'];
  35. $model->userPassword = md5($param['userPassword']);
  36. if ($userInfo = $model->login()) {
  37. $sessionHash = md5(time() . $userInfo->userId);
  38. $userInfo->update([
  39. 'lastLoginIp' => $this->clientRealIP(),
  40. 'lastLoginTime' => time(),
  41. 'userSession' => $sessionHash
  42. ]);
  43. $rs = $userInfo->toArray();
  44. unset($rs['userPassword']);
  45. $rs['userSession'] = $sessionHash;
  46. $this->response()->setCookie('userSession', $sessionHash, time() + 3600, '/');
  47. $this->writeJson(Status::CODE_OK, $rs);
  48. } else {
  49. $this->writeJson(Status::CODE_BAD_REQUEST, '', '密码错误');
  50. }
  51. }
  52. public function logout()
  53. {
  54. $sessionKey = $this->request()->getRequestParam('userSession');
  55. if (empty($sessionKey)) {
  56. $sessionKey = $this->request()->getCookieParams('userSession');
  57. }
  58. if (empty($sessionKey)) {
  59. $this->writeJson(Status::CODE_UNAUTHORIZED, '', '尚未登入');
  60. return false;
  61. }
  62. $result = $this->getWho()->logout();
  63. if ($result) {
  64. $this->writeJson(Status::CODE_OK, '', "登出成功");
  65. } else {
  66. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
  67. }
  68. }
  69. public function getInfo()
  70. {
  71. $this->writeJson(200, $this->getWho(), 'success');
  72. }
  73. }

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

::: warning 管理员登陆:127.0.0.1:9501/Api/Admin/Auth/login?account=xsk&password=123456 公共请求banner:127.0.0.1:9501/Api/Common/Banner/getAll 会员登陆:127.0.0.1:9501/Api/User/Auth/login?userAccount=xsk&userPassword=123456 :::