daycry/restserver

此包已被废弃,不再维护。作者建议使用daycry/restful包代替。

Codeigniter 4的REST服务器

v7.2.10 2023-02-14 15:05 UTC

README

Donate

REST服务器

Codeigniter 4的带有Doctrine的REST服务器

Build Status Coverage Status Downloads GitHub release (latest by date) GitHub stars GitHub license

版本7

此版本与之前的版本不兼容,因为它包含新的自动化功能、数据库重构(使用新的外键),因此如果更新,请检查表名是否使用复数。

通过composer安装

使用composer install安装此包

> composer require daycry/restserver

手动安装

下载此仓库,然后通过编辑app/Config/Autoload.php并添加Daycry\RestServer命名空间到$psr4数组来启用它。例如,如果您将其复制到app/ThirdParty

$psr4 = [
    'Config'      => APPPATH . 'Config',
    APP_NAMESPACE => APPPATH,
    'App'         => APPPATH,
    'Daycry\RestServer' => APPPATH .'ThirdParty/restserver/src',
];

配置

运行命令

> php spark restserver:publish
> php spark settings:publish
> php spark cronjob:publish
> php spark jwt:publish

此命令将复制一个配置文件到您的app命名空间。然后您可以根据需要调整它。默认文件将位于app/Config/RestServer.php

> php spark migrate -all

此命令将在您的数据库中创建REST服务器表。

如果您想加载示例种子,可以使用此命令。

> php spark db:seed Daycry\RestServer\Database\Seeds\ExampleSeeder

有关安装doctrine的更多信息:https://github.com/daycry/doctrine

使用加载库

<?php namespace App\Controllers;

class Center extends \Daycry\RestServer\RestServer
{
    public function index()
    {
        return $this->respond( $this->content );
    }
}

如果您想在控制器调用之前更改属性

<?php namespace App\Controllers;

class Center extends \Daycry\RestServer\RestServer
{
    public function __construct()
    {
        $this->_restConfig = config('RestServer');
        $this->_restConfig->restAjaxOnly = true;
    }

    public function index()
    {
        return $this->respond( $this->content );
    }
}

如果您需要验证数据,您可以调用validation方法,传入字符串规则和您需要的验证配置文件。

例如:app/Config/Validation.php或如果规则在自定义命名空间中,app/Modules/Example/Config/Validation.php

	public $requiredLogin = [
		'username'		=> 'required',
		'password'		=> 'required',
		//'fields'		=> 'required'
	];
<?php namespace App\Controllers;

class Center extends \Daycry\RestServer\RestServer
{
    public function index()
    {
        $this->validation( 'requiredLogin' );
        return $this->respond( $this->content );
    }
}

$this->content包含请求中的主体内容。$this->args包含所有参数,get、post、headers等,但您也可以使用对象$this->request来获取这些参数。

<?php namespace App\Controllers;

class Center extends \Daycry\RestServer\RestServer
{
    public function index()
    {
        $this->validation( 'requiredLogin', config( Example\\Validation ), true, true );
        return $this->respond( $this->content );
    }
}

验证函数参数

字段 描述
规则 规则名称
命名空间 包含规则的命名空间
getShared truefalse
过滤器 如果您想限制主体内容仅限于规则的参数。

用户模型类

默认情况下,您可以通过'\Daycry\RestServer\Models\UserModel'模型将用户与键关联起来,但您可以通过创建现有的'\Daycry\RestServer\Libraries\User\UserAbstract'类来自定义它。

示例

<?php
namespace App\Models;

use Daycry\RestServer\Libraries\User\UserAbstract;

class CustomUserModel extends UserAbstract
{
    protected $DBGroup = 'default';

    protected $table      = 'users';

    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    protected $returnType     = 'object';

    protected $useSoftDeletes = true;

    protected $allowedFields = [ 'name', 'key_id' ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;
}

如果您自定义用户类,您必须修改默认配置

示例

<?php
    public $restUsersTable = 'restserver_user'; //user table name
    public $userModelClass = \Daycry\RestServer\Models\UserModel::class; //user model Class
    public $userKeyColumn = 'key_id'; // column that associates the key 

异常 & 阻止无效尝试

如果您想使用某些自定义异常将其用作失败的请求尝试并允许阻止该IP,您必须创建静态属性 authorized

如果 authorizedfalse,系统将增加该IP的失败尝试次数。示例

<?php

    namespace App\Exceptions;

    use CodeIgniter\Exceptions\FrameworkException;

    class SecretException extends FrameworkException
    {
        protected $code = 401;

        public static $authorized = true;

        public static function forInvalidPassphrase()
        {
            self::$authorized = false;
            return new self(lang('Secret.invalidPassphrase'));
        }

        public static function forInvalidToken()
        {
            self::$authorized = false;
            return new self(lang('Secret.invalidToken'));
        }

        public static function forExpiredToken()
        {
            self::$authorized = false;
            return new self(lang('Secret.tokenExpired'));
        }

        public static function forTokenReaded()
        {
            self::$authorized = false;
            return new self(lang('Secret.readed'));
        }
    }

OPTIONS

您可以使用 petition 表独立地自定义请求。

字段 选项 描述
namespace_id 此字段包含 ws_namespaces 表的标识符,此表存储类的命名空间,例如 \App\Controllers\Auth
method login 使用此字段来配置控制器的操作方法
http post getpostputpatchoptions 使用此字段来配置控制器的操作方法
auth bearer falsebasicdigestbearer 使用此字段来配置认证方法
log null null10 如果您想记录请求,请使用此字段
limit null null115 如果您想设置请求限制,请使用此字段,此值必须为整数
time null null115 此字段用于了解请求限制重置的频率(以秒为单位,例如:3600 -> 在这种情况下,您可以在3600秒内执行{limit}次请求)
level null null110 使用此字段来表示请求的权限级别,如果令牌级别为1,而请求级别为3,则您将无法执行该请求

您可以使用命令自动填充 ws_namespaces

<?php

    php spark restserver:discover

此命令在您指定的命名空间或命名空间中搜索类。您可以在 RestServer.php 配置文件中设置此命名空间。

<?php

    /**
    *--------------------------------------------------------------------------
    * Cronjob
    *--------------------------------------------------------------------------
    *
    * Set to TRUE to enable Cronjob for fill the table petitions with your API classes
    * $restNamespaceScope \Namespace\Class or \Namespace\Folder\Class or \Namespace example: \App\Controllers
    *
    * This feature use Daycry\CronJob vendor
    * for more information: https://github.com/daycry/cronjob
    *
    */
    public string $restApiTable = 'ws_apis';
    public string $restNamespaceTable = 'ws_namespaces';
    public array $restNamespaceScope = ['\App\Controllers', '\Api\Controllers'];

或者创建一个cronjob任务,编辑 CronJob.php 配置文件,如下所示。

<?php

    /*
    |--------------------------------------------------------------------------
    | Cronjobs
    |--------------------------------------------------------------------------
    |
    | Register any tasks within this method for the application.
    | Called by the TaskRunner.
    |
    | @param Scheduler $schedule
    */
    public function init(Scheduler $schedule)
    {
        $schedule->command('restserver:discover')->named('discoverRestserver')->daily();
        or
        $schedule->command('restserver:discover')->named('discoverRestserver')->daily('11:30 am');
    }

有关cronjob的更多信息: https://github.com/daycry/cronjob

响应

默认响应为 json,但您可以在标题中将其更改为 xml

Accept: application/json

Accept: application/xml

或您可以在GET变量中设置格式

http://example.com?format=json
http://example.com?format=xml

请求数据体

请求数据体默认为 json,但您可以更改它。

Content-Type: application/json

Content-Type: application/xml

API令牌

您可以将 api rest token 发送至标题、GET或POST变量,如下所示。

X-API-KEY: TOKEN
http://example.com?X-API-KEY=key

语言

您可以通过这种方式发送 language

Accept-Language: en