title: Basic development example meta:

  • name: description content: EasySwoole basic development example, teach you how to implement an api interface website with easyswoole
  • name: keywords content: swoole|swoole extension|swoole framework|Easyswoole|swoole extension|swoole framework|php coroutine framework

Basic development example

Demo address

The base development example is open source, address: https://github.com/easy-swoole/demo/tree/3.x

Installation

Frame installation

  • We first install the swooole extension, execute php --ri swoole to make sure you can see the swoole extension version is 4.4.8.
  • Create a directory called Test and execute composer require easyswoole/easyswoole=3.x to introduce easyswoole
    • Execute php vendor/bin/easyswoole install to install

Namespace registration

Edit the composer.json file in the Test root directory and add "App\\": "App/". The general structure is as follows:

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

Post-installation directory structure

  1. Test Project deployment directory
  2. ├─App Application directory
  3. ├─HttpController Controller directory (need to create it yourself)
  4. ├─Log Log file directory (created after startup)
  5. ├─Temp Temporary file directory (created after startup)
  6. ├─vendor Third-party class library directory
  7. ├─composer.json Composer architecture
  8. ├─composer.lock Composer lock
  9. ├─EasySwooleEvent.php Framework global event
  10. ├─easyswoole Framework management script
  11. ├─easyswoole.install Frame installation lock file
  12. ├─dev.php Development configuration file
  13. ├─produce.php Production profile

Execute the following command to update the namespace:

  1. composer dumpautoload

Connection pool implementation

Configuration item

In the dev.php configuration file, add the following configuration information, note: Please follow your own mysql server information to fill in the account password .

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

Introducing the ORM library

Execute the following command to implement the introduction of the ORM library.

  1. composer require easyswoole/orm

Event registration

We edit the EasySwooleEvent.php file in the root directory and register the ORM connection in the `mainServerCreate event. The general structure is as follows:

  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. // TODO: Time zone configuration
  20. date_default_timezone_set('Asia/Shanghai');
  21. }
  22. public static function mainServerCreate(EventRegister $register)
  23. {
  24. $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
  25. DbManager::getInstance()->addConnection(new Connection($config));
  26. }
  27. public static function onRequest(Request $request, Response $response): bool
  28. {
  29. // TODO: Implement onRequest() method.
  30. return true;
  31. }
  32. public static function afterRequest(Request $request, Response $response): void
  33. {
  34. // TODO: Implement afterAction() method.
  35. }
  36. }

::: warning Register the database connection pool in the initialize event, this $config can configure the connection pool size, etc. :::

Model definition

Administrator model

Add administrator user table:

  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', 'Alan', 'xsk', 'e10adc3949ba59abbe56e057f20f883e', '', '1566279458', '192.168.159.1');

Add a model file

Add the App/Model/Admin/AdminModel.php file:

  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. $where['adminAccount'] = ['%' . $keyword . '%','like'];
  32. }
  33. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  34. $total = $this->lastQueryResult()->getTotalCount();
  35. return ['total' => $total, 'list' => $list];
  36. }
  37. /*
  38. * After the login is successful, please return to the updated bean.
  39. */
  40. function login():?AdminModel
  41. {
  42. $info = $this->get(['adminAccount'=>$this->adminAccount,'adminPassword'=>$this->adminPassword]);
  43. return $info;
  44. }
  45. /*
  46. * Query by account
  47. */
  48. function accountExist($field='*'):?AdminModel
  49. {
  50. $info = $this->field($field)->get(['adminAccount'=>$this->adminAccount]);
  51. return $info;
  52. }
  53. function getOneBySession($field='*'):?AdminModel
  54. {
  55. $info = $this->field($field)->get(['adminSession'=>$this->adminSession]);
  56. return $info;
  57. }
  58. function logout()
  59. {
  60. return $this->update(['adminSession'=>'']);
  61. }
  62. }

::: warning The definition of model can be viewed in the orm chapter ::: ::: warning Regarding the ide automatic prompt, as long as you add @property $adminId ide to the class comment above, you can automatically prompt this property of the class. :::

Ordinary user model

Common user model and administrator model are the same

Building a table

  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 'User balance',
  13. `frozenMoney` int(10) NOT NULL DEFAULT '0' COMMENT 'Freeze balance',
  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', 'Alan', 'xsk', 'e10adc3949ba59abbe56e057f20f883e', '', '1566279458', '192.168.159.1','1566279458','',1,'1','1');

Add a model file

Add the App/Model/User/UserModel.php file:

  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;//Disabled state
  24. const STATE_NORMAL = 1;//normal status
  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. $where['userAccount'] = ['%' . $keyword . '%','like'];
  38. }
  39. $list = $this->limit($pageSize * ($page - 1), $pageSize)->order($this->primaryKey, 'DESC')->withTotalCount()->all($where);
  40. $total = $this->lastQueryResult()->getTotalCount();
  41. return ['total' => $total, 'list' => $list];
  42. }
  43. public function getOneByPhone($field='*'): ?UserModel
  44. {
  45. $info = $this->field($field)->get(['phone'=>$this->phone]);
  46. return $info;
  47. }
  48. /*
  49. * After the login is successful, please return to the updated bean.
  50. */
  51. function login():?UserModel
  52. {
  53. $info = $this->get(['userAccount'=>$this->userAccount,'userPassword'=>$this->userPassword]);
  54. return $info;
  55. }
  56. function getOneBySession($field='*'):?UserModel
  57. {
  58. $info = $this->field($field)->get(['userSession'=>$this->userSession]);
  59. return $info;
  60. }
  61. function logout(){
  62. return $this->update(['userSession'=>'']);
  63. }
  64. }

Banner model

Building a table

  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 image',
  5. `bannerDescription` varchar(255) DEFAULT NULL,
  6. `bannerUrl` varchar(255) DEFAULT NULL COMMENT 'Jump address',
  7. `state` tinyint(3) DEFAULT NULL COMMENT 'State 0 hidden 1 normal',
  8. PRIMARY KEY (`bannerId`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  10. INSERT INTO `banner_list` VALUES ('1', 'Test banner', 'asdadsasdasd.jpg', 'Tested banner data', 'www.php20.cn',1);

Add a model file

Added App/Model/Admin/BannerModel.php file:

  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. }

Controller definition

Global base controller definition

Add the App/Httpcontroller/BaseController file:

  1. <?php
  2. namespace App\HttpController;
  3. use EasySwoole\EasySwoole\ServerManager;
  4. use EasySwoole\Http\AbstractInterface\AnnotationController;
  5. class BaseController extends AnnotationController
  6. {
  7. function index()
  8. {
  9. $this->actionNotFound('index');
  10. }
  11. /**
  12. * Get the user's real IP
  13. * @param string $headerName The header name passed by the proxy server
  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)) { // If there is xri, it is judged that the front end has an agent such as NGINX.
  25. $clientAddress = $xri[0];
  26. } elseif (!empty($xff)) { // If there is no xri, continue to judge 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. $value = $this->request()->getRequestParam($name);
  35. return $value ?? $default;
  36. }
  37. }

::: warning New base controller, the method inside is used to get user ip, and get api parameters
:::

::: warning The base controller inherits EasySwoole\Http\AbstractInterface\AnnotationController, this is an annotation support controller, which can be viewed in the annotation section. :::

Api base controller definition

Added App/Httpcontroller/Api/ApiBase.php file:

  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. 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. 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, 'Internal system error, please try again later');
  43. }
  44. }
  45. }
  46. }

::: warning Api base class controller for intercepting annotation exceptions and api exceptions, returning a json format error message to the user :::

Common base controller definition

Added App/Httpcontroller/Api/Common/CommonBase.php file:

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

Public controller

The public controller puts the controller that can be viewed without logging in, such as the banner list view:

Added App/HttpController/Api/Common/Banner.php file:

  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="Primary key 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="Number of pages", optional="", integer="")
  38. * @Param(name="limit", alias="Total number of pages", optional="", integer="")
  39. * @Param(name="keyword", alias="Keyword", 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 It can be seen that in the getAll method, there is a comment of @Param(name="page", alias="page number", optional="", integer=""), this is an annotation support writing method, and can be written. Can not write, after writing this comment, will constrain the page parameter must be int, the specific verification mechanism can be viewed validate validator :::

::: warning Test link: 127.0.0.1:9501/api/common/banner/getAll :::

::: warning Need to have data to see the specific output :::

Administrator base controller definition

Add the App/HttpController/Api/Admin/AdminBase.php file:

  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 will be cleared according to the coroutine
  15. public $who;
  16. //Session cookie header
  17. protected $sessionKey = 'adminSession';
  18. //whitelist
  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. function onRequest(?string $action): ?bool
  29. {
  30. if (parent::onRequest($action)) {
  31. //White list judgment
  32. if (in_array($action, $this->whiteList)) {
  33. return true;
  34. }
  35. //Get login information
  36. if (!$this->getWho()) {
  37. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'Login has expired');
  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. 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. }

Administrator login controller

Added App/HttpController/Api/Admin/Auth.php file:

  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. * Login, parameter verification annotation
  18. * @Param(name="account", alias="account number", required="", lengthMax="20")
  19. * @Param(name="password", alias="password", required="", lengthMin="6", lengthMax="16")
  20. * @throws \EasySwoole\ORM\Exception\Exception
  21. * @throws \Throwable
  22. * @author Tioncico
  23. * Time: 10:18
  24. */
  25. 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, '', 'wrong password');
  45. }
  46. }
  47. /**
  48. * logout
  49. * Logout, parameter annotation
  50. * @Param(name="adminSession", from={COOKIE}, required="")
  51. * @return bool
  52. * @author Tioncico
  53. * Time: 10:23
  54. */
  55. 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, '', 'Not logged in');
  63. return false;
  64. }
  65. $result = $this->getWho()->logout();
  66. if ($result) {
  67. $this->writeJson(Status::CODE_OK, '', "exit successfully");
  68. } else {
  69. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
  70. }
  71. }
  72. function getInfo()
  73. {
  74. $this->writeJson(200, $this->getWho()->toArray(), 'success');
  75. }
  76. }

::: warning It can be seen that in the getAll method, there is a comment of @Param(name="account", alias="account", required="", lengthMax="20"), this is an annotation support writing method, and can be written as well. Can not write, after writing this comment, will constrain the page parameter must be int, the specific verification mechanism can be viewed validate validator :::

::: warning Request 127.0.0.1:9501/Api/Admin/Auth/login?account=xsk&password=123456 to return: :::

  1. {
  2. "code": 200,
  3. "result": {
  4. "adminId": 1,
  5. "adminName": "Alan",
  6. "adminAccount": "xsk",
  7. "adminSession": "d45de0cd6dd91122db4bd7e976c7deb8",
  8. "adminLastLoginTime": 1566279458,
  9. "adminLastLoginIp": "192.168.159.1"
  10. },
  11. "msg": null
  12. }

Administrator user management controller

Add the App/httpController/Api/Admin/User.php file:

  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="Number of pages", optional="", integer="")
  19. * @Param(name="limit", alias="Total number of pages", optional="", integer="")
  20. * @Param(name="keyword", alias="Keyword", optional="", lengthMax="32")
  21. * @author Tioncico
  22. * Time: 14:01
  23. */
  24. 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="User id", required="", integer="")
  35. * @throws \EasySwoole\ORM\Exception\Exception
  36. * @throws \Throwable
  37. * @author Tioncico
  38. * Time: 11:48
  39. */
  40. 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="User's Nickname", optional="", lengthMax="32")
  55. * @Param(name="userAccount", alias="username", required="", lengthMax="32")
  56. * @Param(name="userPassword", alias="user password", required="", lengthMin="6",lengthMax="18")
  57. * @Param(name="phone", alias="cellphone number", optional="", lengthMax="18",numeric="")
  58. * @Param(name="state", alias="user status", optional="", inArray="{0,1}")
  59. * @author Tioncico
  60. * Time: 11:48
  61. */
  62. 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="User id", required="", integer="")
  77. * @Param(name="userPassword", alias="member password", optional="", lengthMin="6",lengthMax="18")
  78. * @Param(name="userName", alias="Member name", optional="", lengthMax="32")
  79. * @Param(name="state", alias="status", optional="", inArray="{0,1}")
  80. * @Param(name="phone", alias="phone number", optional="", lengthMax="18")
  81. * @throws \EasySwoole\ORM\Exception\Exception
  82. * @throws \Throwable
  83. * @author Tioncico
  84. * Time: 11:54
  85. */
  86. 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, [], 'This member was not found');
  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="User id", required="", integer="")
  114. * @throws \EasySwoole\ORM\Exception\Exception
  115. * @throws \Throwable
  116. * @author Tioncico
  117. * Time: 14:02
  118. */
  119. 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, [], 'failed to delete');
  129. }
  130. }
  131. }

::: warning After the background administrator logs in, you can use the interface of this file to perform the curd member.
:::

::: warning The request address is: 127.0.0.1:9501/Api/Admin/User/getAll (etc.)
:::

Normal user base controller definition

Added App/HttpController/Api/User/UserBase.php file:

  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\MysqlPool;
  13. use App\Utility\Pool\RedisPool;
  14. use EasySwoole\Http\Message\Status;
  15. use EasySwoole\MysqliPool\Mysql;
  16. use EasySwoole\Spl\SplBean;
  17. use EasySwoole\Validate\Validate;
  18. class UserBase extends ApiBase
  19. {
  20. protected $who;
  21. //Session cookie header
  22. protected $sessionKey = 'userSession';
  23. //whitelist
  24. protected $whiteList = ['login', 'register'];
  25. /**
  26. * onRequest
  27. * @param null|string $action
  28. * @return bool|null
  29. * @throws \Throwable
  30. * @author yangzhenyu
  31. * Time: 13:49
  32. */
  33. function onRequest(?string $action): ?bool
  34. {
  35. if (parent::onRequest($action)) {
  36. //White list judgment
  37. if (in_array($action, $this->whiteList)) {
  38. return true;
  39. }
  40. //Get login information
  41. if (!$data = $this->getWho()) {
  42. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'Login has expired');
  43. return false;
  44. }
  45. //Refresh cookie survival
  46. $this->response()->setCookie($this->sessionKey, $data->getUserSession(), time() + 3600, '/');
  47. return true;
  48. }
  49. return false;
  50. }
  51. /**
  52. * getWho
  53. * @author yangzhenyu
  54. * Time: 13:51
  55. */
  56. function getWho(): ?UserModel
  57. {
  58. if ($this->who instanceof UserModel) {
  59. return $this->who;
  60. }
  61. $sessionKey = $this->request()->getRequestParam($this->sessionKey);
  62. if (empty($sessionKey)) {
  63. $sessionKey = $this->request()->getCookieParams($this->sessionKey);
  64. }
  65. if (empty($sessionKey)) {
  66. return null;
  67. }
  68. $userModel = new UserModel();
  69. $userModel->userSession = $sessionKey;
  70. $this->who = $userModel->getOneBySession();
  71. return $this->who;
  72. }
  73. }

Ordinary user login controller

Added App/HttpController/Api/User/Auth.php file:

  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\Pool\MysqlPool;
  13. use App\Utility\SwooleApi\User\Login;
  14. use EasySwoole\Http\Annotation\Param;
  15. use EasySwoole\Http\Message\Status;
  16. use EasySwoole\MysqliPool\Mysql;
  17. use EasySwoole\Spl\SplBean;
  18. use EasySwoole\Validate\Validate;
  19. class Auth extends UserBase
  20. {
  21. protected $whiteList = ['login', 'register'];
  22. /**
  23. * login
  24. * @Param(name="userAccount", alias="username", required="", lengthMax="32")
  25. * @Param(name="userPassword", alias="password", required="", lengthMin="6",lengthMax="18")
  26. * @throws \EasySwoole\ORM\Exception\Exception
  27. * @throws \Throwable
  28. * @author Tioncico
  29. * Time: 15:06
  30. */
  31. function login()
  32. {
  33. $param = $this->request()->getRequestParam();
  34. $model = new UserModel();
  35. $model->userAccount = $param['userAccount'];
  36. $model->userPassword = md5($param['userPassword']);
  37. if ($userInfo = $model->login()) {
  38. $sessionHash = md5(time() . $userInfo->userId);
  39. $userInfo->update([
  40. 'lastLoginIp' => $this->clientRealIP(),
  41. 'lastLoginTime' => time(),
  42. 'userSession' => $sessionHash
  43. ]);
  44. $rs = $userInfo->toArray();
  45. unset($rs['userPassword']);
  46. $rs['userSession'] = $sessionHash;
  47. $this->response()->setCookie('userSession', $sessionHash, time() + 3600, '/');
  48. $this->writeJson(Status::CODE_OK, $rs);
  49. } else {
  50. $this->writeJson(Status::CODE_BAD_REQUEST, '', 'wrong password');
  51. }
  52. }
  53. function logout()
  54. {
  55. $sessionKey = $this->request()->getRequestParam('userSession');
  56. if (empty($sessionKey)) {
  57. $sessionKey = $this->request()->getCookieParams('userSession');
  58. }
  59. if (empty($sessionKey)) {
  60. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'Not signed');
  61. return false;
  62. }
  63. $result = $this->getWho()->logout();
  64. if ($result) {
  65. $this->writeJson(Status::CODE_OK, '', "Logout success");
  66. } else {
  67. $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
  68. }
  69. }
  70. function getInfo()
  71. {
  72. $this->writeJson(200, $this->getWho(), 'success');
  73. }
  74. }

You can log in successfully by accessing 127.0.0.1:9501/Api/User/Auth/login?userAccount=xsk&userPassword=123456

::: warning Administrator login: 127.0.0.1:9501/Api/Admin/Auth/login?account=xsk&password=123456 Public request banner:127.0.0.1:9501/Api/Common/Banner/getAll Member login: 127.0.0.1:9501/Api/User/Auth/login?userAccount=xsk&userPassword=123456 :::