前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >easyswoole快速实现一个网站的api接口程序

easyswoole快速实现一个网站的api接口程序

作者头像
仙士可
发布2019-12-19 14:49:21
1.4K0
发布2019-12-19 14:49:21
举报
文章被收录于专栏:仙士可博客

目前,easyswoole已经成为了最知名的swoole框架之一,本人也用easyswoole开发过很多个项目了,现在就来讲一讲如何用easyswoole快速实现一个网站的curd功能的接口。

安装easyswoole和相关组件

环境方面本人不多做说明,可以去官方文档查看。

新增composer.json文件

代码语言:javascript
复制
{
    "require": {
        "easyswoole/easyswoole": "^3.2",
        "easyswoole/mysqli": "^1.2",
        "tioncico/curd-automatic-generation": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "Application/"
        }
    }
}

然后输入以下命令进行引入,安装组件库:

代码语言:javascript
复制
composer up
mkdir -p Application/HttpController
php ./vendor/easyswoole/easyswoole/bin/easyswoole install

设计数据表

假设我们需要做一个简单的文章管理系统,需要用户,文章,评论,置顶,分类,这5个表:

新增文件 test.php

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 19-7-27
 * Time: 上午11:40
 */

include "./vendor/autoload.php";
//会员列表
$result = \EasySwoole\Mysqli\DDLBuilder\DDLBuilder::table('user_list', function (\EasySwoole\Mysqli\DDLBuilder\Blueprints\TableBlueprint $blueprint) {
    $blueprint->colInt('id', '11')->setColumnComment('主键id')->setIsPrimaryKey()->setIsAutoIncrement();
    $blueprint->colVarChar('userAccount', '32')->setColumnComment('会员账号');
    $blueprint->colVarChar('userName', '32')->setColumnComment('会员昵称');
    $blueprint->colVarChar('userPassword', '32')->setColumnComment('会员密码');
    $blueprint->colDateTime('addTime')->setColumnComment('新增时间');
    $blueprint->colTinyInt('isAdmin', 1)->setColumnComment('是否会管理员')->setDefaultValue(0);
    $blueprint->setTableComment('会员列表');
    $blueprint->setTableEngine(\EasySwoole\Mysqli\DDLBuilder\Enum\Engines::INNODB);
    $blueprint->setTableCharset(\EasySwoole\Mysqli\DDLBuilder\Enum\Character::UTF8_GENERAL_CI);
    $blueprint->indexNormal('userAccount', ['userAccount']);
});
echo $result;

//文章分类列表
$result = \EasySwoole\Mysqli\DDLBuilder\DDLBuilder::table('article_list', function (\EasySwoole\Mysqli\DDLBuilder\Blueprints\TableBlueprint $blueprint) {
    $blueprint->colInt('id', '11')->setColumnComment('主键id')->setIsPrimaryKey()->setIsAutoIncrement();
    $blueprint->colInt('pid', 11)->setColumnComment('上级id');
    $blueprint->colVarChar('categoryName', '64')->setColumnComment('分类名称');
    $blueprint->setTableComment('分类列表');
    $blueprint->setTableEngine(\EasySwoole\Mysqli\DDLBuilder\Enum\Engines::INNODB);
    $blueprint->setTableCharset(\EasySwoole\Mysqli\DDLBuilder\Enum\Character::UTF8_GENERAL_CI);
});
echo $result;

//文章列表
$result = \EasySwoole\Mysqli\DDLBuilder\DDLBuilder::table('article_list', function (\EasySwoole\Mysqli\DDLBuilder\Blueprints\TableBlueprint $blueprint) {
    $blueprint->colInt('id', '11')->setColumnComment('主键id')->setIsPrimaryKey()->setIsAutoIncrement();
    $blueprint->colInt('categoryId', 11)->setColumnComment('分类id');
    $blueprint->colVarChar('title', '64')->setColumnComment('标题');
    $blueprint->colVarChar('keyword', '64')->setColumnComment('关键字');
    $blueprint->colVarChar('description', '255')->setColumnComment('简介');
    $blueprint->colVarChar('author', '32')->setColumnComment('作者');
    $blueprint->colText('content')->setColumnComment('内容');
    $blueprint->colDateTime('addTime')->setColumnComment('新增时间');
    $blueprint->colTinyInt('isOriginal', 1)->setColumnComment('是否原创')->setDefaultValue(1);
    $blueprint->setTableComment('文章列表');
    $blueprint->setTableEngine(\EasySwoole\Mysqli\DDLBuilder\Enum\Engines::INNODB);
    $blueprint->setTableCharset(\EasySwoole\Mysqli\DDLBuilder\Enum\Character::UTF8_GENERAL_CI);
    $blueprint->indexNormal('title', ['title']);
});
echo $result;

//评论列表
$result = \EasySwoole\Mysqli\DDLBuilder\DDLBuilder::table('comment_list', function (\EasySwoole\Mysqli\DDLBuilder\Blueprints\TableBlueprint $blueprint) {
    $blueprint->colInt('id', '11')->setColumnComment('主键id')->setIsPrimaryKey()->setIsAutoIncrement();
    $blueprint->colInt('articleId', 11)->setColumnComment('文章id');
    $blueprint->colInt('commentPid', 11)->setColumnComment('评论父id')->setDefaultValue(0);
    $blueprint->colInt('userId', 11)->setColumnComment('评论会员id');
    $blueprint->colVarChar('userName', '64')->setColumnComment('评论会员名');
    $blueprint->colVarChar('content', '255')->setColumnComment('评论内容');
    $blueprint->colDateTime('addTime')->setColumnComment('评论时间');
    $blueprint->setTableComment('文章评论列表');
    $blueprint->setTableEngine(\EasySwoole\Mysqli\DDLBuilder\Enum\Engines::INNODB);
    $blueprint->setTableCharset(\EasySwoole\Mysqli\DDLBuilder\Enum\Character::UTF8_GENERAL_CI);
    $blueprint->indexNormal('articleId', ['articleId']);
    $blueprint->indexNormal('commentPid', ['commentPid']);
    $blueprint->indexNormal('userId', ['userId']);
});
echo $result;

//评论列表
$result = \EasySwoole\Mysqli\DDLBuilder\DDLBuilder::table('top_list', function (\EasySwoole\Mysqli\DDLBuilder\Blueprints\TableBlueprint $blueprint) {
    $blueprint->colInt('id', '11')->setColumnComment('主键id')->setIsPrimaryKey()->setIsAutoIncrement();
    $blueprint->colInt('articleId', 11)->setColumnComment('文章id');
    $blueprint->setTableComment('文章置顶列表');
    $blueprint->setTableEngine(\EasySwoole\Mysqli\DDLBuilder\Enum\Engines::INNODB);
    $blueprint->setTableCharset(\EasySwoole\Mysqli\DDLBuilder\Enum\Character::UTF8_GENERAL_CI);
    $blueprint->indexNormal('articleId', ['articleId']);
});
echo $result;

该文件作用是直接通过easyswoole的mysqli建表工具生成建表sql,运行sql直接建表

配置数据库

在dev.php文件中新增以下配置:

代码语言:javascript
复制
'MYSQL'       => [
    'host'            => '127.0.0.1',
    'port'            => 3306,
    'user'            => 'root',
    'password'        => 'test',
    'database'        => 'article',
    'timeout'         => 30,
    'charset'         => 'utf8mb4',
    'connect_timeout' => '5',//连接超时时间
],

注册数据库连接池:

在easyswooleEvent.php的initialize方法中,注册数据库连接池:

代码语言:javascript
复制
public static function initialize()
{
    // TODO: Implement initialize() method.
    date_default_timezone_set('Asia/Shanghai');
    $mysqlConfig = new \EasySwoole\Mysqli\Config(\EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL'));
    \EasySwoole\MysqliPool\Mysql::getInstance()->register('mysql',$mysqlConfig);
}

初始化basemodel和basecontroller:

新增init.php文件:

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 19-7-27
 * Time: 上午11:59
 */
include "./vendor/autoload.php";
\EasySwoole\EasySwoole\Core::getInstance()->initialize();
$init = new \AutomaticGeneration\Init();
$init->initBaseModel();
$init->initBaseController();

该脚本可在App目录中生成基础的baseModel和baseController

新增AdminBase,IndexBase,UserBase控制器,用于控制登录权限

分别在//Application/HttpController/Api/Admin,/Api/User,/Api/Index中新增Base.php文件:

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 19-7-27
 * Time: 下午12:14
 */

namespace App\HttpController\Api\Admin;


use App\Model\UserBean;
use EasySwoole\Http\Message\Status;

class Base extends \App\HttpController\Base
{

    protected $who;
    //session的cookie头
    protected $tokenName = 'adminSession';
    //白名单,用于用户请求login方法时,不会因为没有登录而拒绝访问
    protected $whiteList = ['login'];

    /**
     * onRequest
     * @param null|string $action
     * @return bool|null
     * @throws \Throwable
     * @author yangzhenyu
     * Time: 13:49
     */
    function onRequest(?string $action): ?bool
    {
        if (parent::onRequest($action)) {
            //白名单判断
            if (in_array($action, $this->whiteList)) {
                return true;
            }
            //获取登入信息,如果没有登录,则不让访问,只有Admin和User需要
            if (!$this->getWho()) {
                $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * getWho
     * @return bool
     * @author yangzhenyu
     * Time: 13:51
     */
    function getWho(): ?UserBean
    {
        if ($this->who instanceof UserBean) {
            return $this->who;
        }
        $sessionKey = $this->request()->getRequestParam($this->tokenName);
        if (empty($sessionKey)) {
            $sessionKey = $this->request()->getCookieParams($this->tokenName);
        }
        if (empty($sessionKey)) {
            return null;
        }
        //这里需要自己实现,通过用户传来的token,去获取用户信息,如果获取失败,则代表没有登录
        return $this->who;
    }
    protected function getValidateRule(?string $action): ?\EasySwoole\Validate\Validate
    {
        // TODO: Implement getValidateRule() method.
    }


}

批量新增curd控制器,表操作model

新增createTable.php文件:

代码语言:javascript
复制
<?php
/**
 * Created by PhpStorm.
 * User: tioncico
 * Date: 19-7-27
 * Time: 上午11:59
 */
include "./vendor/autoload.php";
\EasySwoole\EasySwoole\Core::getInstance()->initialize();

go(function () {
    $db = \EasySwoole\MysqliPool\Mysql::defer('mysql');
    $result = $db->rawQuery("show tables;");
    $tableList = array_column($result,'Tables_in_article');
    var_dump($tableList);
    //生成所有的bean,model

    foreach ($tableList as $tableName){
        var_dump($tableName);
        $mysqlTable = new \AutomaticGeneration\MysqlTable($db, \EasySwoole\EasySwoole\Config::getInstance()->getConf('MYSQL.database'));
        $tableColumns = $mysqlTable->getColumnList($tableName);
        $tableComment = $mysqlTable->getComment($tableName);
        $path = '';
        $beanConfig = new \AutomaticGeneration\Config\BeanConfig();
        $beanConfig->setBaseNamespace("App\\Model".$path);
        $beanConfig->setTablePre('');
        $beanConfig->setTableName($tableName);
        $beanConfig->setTableComment($tableComment);
        $beanConfig->setTableColumns($tableColumns);
        $beanBuilder = new \AutomaticGeneration\BeanBuilder($beanConfig);
        $result = $beanBuilder->generateBean();
        var_dump($result);
        $path = '';
        $modelConfig = new \AutomaticGeneration\Config\ModelConfig();
        $modelConfig->setBaseNamespace("App\\Model".$path);
        $modelConfig->setTablePre("");
        $modelConfig->setExtendClass(\App\Model\BaseModel::class);
        $modelConfig->setTableName("user_list");
        $modelConfig->setTableComment($tableComment);
        $modelConfig->setTableColumns($tableColumns);
        $modelBuilder = new \AutomaticGeneration\ModelBuilder($modelConfig);
        $result = $modelBuilder->generateModel();
        var_dump($result);
        $path='\\Api\\Admin';
        $controllerConfig = new \AutomaticGeneration\Config\ControllerConfig();
        $controllerConfig->setBaseNamespace("App\\HttpController".$path);
        $controllerConfig->setTablePre('');
        $controllerConfig->setTableName($tableName);
        $controllerConfig->setTableComment($tableComment);
        $controllerConfig->setTableColumns($tableColumns);
        $controllerConfig->setExtendClass("App\\HttpController".$path."\\Base");
        $controllerConfig->setModelClass($modelBuilder->getClassName());
        $controllerConfig->setBeanClass($beanBuilder->getClassName());
        $controllerConfig->setMysqlPoolClass(EasySwoole\MysqliPool\Mysql::class);
        $controllerConfig->setMysqlPoolName('mysql');
        $controllerBuilder = new \AutomaticGeneration\ControllerBuilder($controllerConfig);
        $result = $controllerBuilder->generateController();
        var_dump($result);

        $path='\\Api\\Index';
        $controllerConfig = new \AutomaticGeneration\Config\ControllerConfig();
        $controllerConfig->setBaseNamespace("App\\HttpController".$path);
        $controllerConfig->setTablePre('');
        $controllerConfig->setTableName($tableName);
        $controllerConfig->setTableComment($tableComment);
        $controllerConfig->setTableColumns($tableColumns);
        $controllerConfig->setExtendClass("App\\HttpController".$path."\\Base");
        $controllerConfig->setModelClass($modelBuilder->getClassName());
        $controllerConfig->setBeanClass($beanBuilder->getClassName());
        $controllerConfig->setMysqlPoolClass(EasySwoole\MysqliPool\Mysql::class);
        $controllerConfig->setMysqlPoolName('mysql');
        $controllerBuilder = new \AutomaticGeneration\ControllerBuilder($controllerConfig);
        $result = $controllerBuilder->generateController();
        var_dump($result);
        $path='\\Api\\User';
        $controllerConfig = new \AutomaticGeneration\Config\ControllerConfig();
        $controllerConfig->setBaseNamespace("App\\HttpController".$path);
        $controllerConfig->setTablePre('');
        $controllerConfig->setTableName($tableName);
        $controllerConfig->setTableComment($tableComment);
        $controllerConfig->setTableColumns($tableColumns);
        $controllerConfig->setExtendClass("App\\HttpController".$path."\\Base");
        $controllerConfig->setModelClass($modelBuilder->getClassName());
        $controllerConfig->setBeanClass($beanBuilder->getClassName());
        $controllerConfig->setMysqlPoolClass(EasySwoole\MysqliPool\Mysql::class);
        $controllerConfig->setMysqlPoolName('mysql');
        $controllerBuilder = new \AutomaticGeneration\ControllerBuilder($controllerConfig);
        $result = $controllerBuilder->generateController();
        var_dump($result);
    }
    exit;
});

运行,根据提示去输入需要在getAll时查询的关键字字段,不填也行:

当前台传入keyword=“测试”,那么sql语句将会生成 title like "%测试%"

完善接口

当这个文件运行完之后,一个文章管理系统的基本api已经是生成好了,大概是这样:

我们下一步要做的是:

1:完善用户登录接口

2:把User里面所有控制器的update,add等方法删除(普通用户没权限管理文章,文章分类等等,当然评论有权限)

3:每个方法都需要去修改下,毕竟自动生成工具不是那么智能,只能自己继续完善了,但是,已经是很好了,不是吗?

4:每个控制器的getValidateRule方法需要自己完善,这个是用于验证用户传入的基础参数是否正确的方法

给你们看看curd的各种方法自动生成后的截图:

这些都是自动生成的哦!

其他:

建表工具文档:https://www.easyswoole.com/Cn/Components/Mysqli/createTable.html

自动生成curd控制器组件地址:https://github.com/tioncico/curdAutomaticGeneration

easyswoole mysql-pool组件:https://www.easyswoole.com/Cn/Components/mysqlPool.html

easyswoole官方文档:https://www.easyswoole.com/Cn/Introduction/environment.html

本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/07/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装easyswoole和相关组件
  • 设计数据表
  • 配置数据库
  • 注册数据库连接池:
  • 初始化basemodel和basecontroller:
  • 新增AdminBase,IndexBase,UserBase控制器,用于控制登录权限
  • 批量新增curd控制器,表操作model
  • 完善接口
  • 其他:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档