ashimbadrie/lara-core

此包的最新版本(dev-main)没有可用的许可证信息。

包含基础类以及辅助类,可快速推进开发。

dev-main 2021-10-14 01:57 UTC

This package is auto-updated.

Last update: 2024-09-14 08:38:49 UTC


README

使用这些便捷的基础类,快速轻松地为 Laravel API 创建 CRUD。

安装

composer require ashimbadrie/lara-core

先决条件

此包期望您的数据库迁移包括以下所需字段。默认情况下,我们已关闭 Laravel 的时间戳使用,并选择使用我们的自定义创建/更新 UNIX 时间戳。我们还添加了记录创建/更新的能力,一旦认证。

$table->integer('created_by')->nullable()->comment('User who created the record');
$table->integer('created_on')->nullable()->comment('The date of creation in unix timestamp');
$table->integer('modified_by')->nullable()->comment('User who modified the record');
$table->integer('modified_on')->nullable()->comment('The date of modification in unix timestamp');

创建数据模型

数据模型是创建数据库表中记录的入口点。当记录被保存时,模型会跟踪哪个 认证用户 创建/修改 记录,并跟踪这些操作的 UNIX 时间戳

创建数据模型非常简单,如下所示

class ExampleModel extends BaseModel {

  protected $table = 'example_table';
  
  protected function defaultLookupField(): String
  {
      return '';
  }
  
}

REST API CRUD

为了处理基本的 REST API CRUD 操作,我们需要创建一个 数据管理器数据控制器,如下所示

class ExampleManager extends DataManager {

  public function __construct()
  {
      $model = "App\Models\ExampleModel"; // Path to the ExampleModel we created above
      parent::__construct($model);
  }
  
}

class ExampleController extends DataController {

  private $exampleManager;

  public function __construct()
  {
      $this->exampleManager = new ExampleManager();
      parent::__construct($this->exampleManager);
  }
  
}

一旦我们设置了我们的 数据模型数据控制器数据管理器,我们就可以创建我们的 API 资源,将其指向 CRUD 逻辑。在 routes/api.php 文件中,我们添加以下内容

Route::get('examples/{id}', 'ExampleController@show');
Route::post('examples', 'ExampleController@store');
Route::patch('examples/{id}', 'ExampleController@update');
Route::delete('examples/{id}', 'ExampleController@destroy');

分页记录列表

为了加载分页的记录列表,我们需要创建一个 列表管理器列表控制器,如下所示

class ExampleListManager extends DataListManager
{
    public function __construct()
    {
        $model = "App\Models\Example";
        parent::__construct($model);
    }
}

class ExampleListController extends DataListController
{
    private $exampleListManager; 
    
    public function __construct()
    {
        $this->exampleListManager = new ExampleListManager();
        parent::__construct($this->exampleListManager);
    }
}

一旦我们有了我们的 数据列表控制器数据列表管理器,我们就可以创建我们的 API 资源,将其指向列表逻辑。在 routes/api.php 文件中,我们添加以下内容

Route::post('examples/list', 'ExampleListController@page');
Route::get('examples/list', 'ExampleListController@index');

列表 post 请求接受一个 application/json 负载,以加载第一页,如下所示

{
  "start": 0,
  "limit": 10,
  "sort_by": {},
  "filter_by": {}
}

注意:您的前端需要在上面的负载中递增起始值,以便遍历分页列表。

一个典型的响应如下所示

{
  "page": [],
  "total": 0
}

向列表添加过滤器

待办事项

对列表进行排序

待办事项