ratiw/api

一个简单的 Laravel API 包。

dev-master 2015-02-13 04:26 UTC

This package is not auto-updated.

Last update: 2024-09-24 04:01:39 UTC


README

这是一个基于 Fractal 的简单 Laravel 基础 API 包。目前,Laravel 5 尚未正式发布,因此此包基于 Laravel 4.2。

此包通过使用 The PHP Leagues 的 Fractal 作为底层引擎,简化了 API 请求构建和转换。

要使用它,您只需遵循以下 3 个步骤

  • 通过扩展 Ratiw\Api\BaseApiController 类创建 API 端点。
  • 通过扩展 Ratiw\Api\BaseTransformer 类创建转换器。
  • 为它创建一个路由。

安装

可以通过 composer 来安装

"require": {
    "ratiw/api": "dev-master"
}

此包需要 Laravel 框架 v4.2 和 Fractal v0.9.*,因此将自动引入

用法

####假设

  • API 代码将位于 Api 目录。
  • composer.json 中定义了以下 PSR-4 命名空间
	...
	"autoload": {
		"psr-4": {
			"Api\\": "app/Api",
			"Entities\\": "app/Entities"
		}
	}
	...
  • API 类将放置在 Api\Controllers 目录。
  • 转换器类将放置在 Api\Transformers 目录。
  • 存在一个简单的基于 Client eloquent 的类,位于 `Entities\Clients` 目录。
<?php namespace Entities\Clients;

class Client extends \Eloquent
{
	protected $table = 'clients';

	public function saleRep()
	{
		return $this->belongsTo('Entities\Staffs\Sale', 'sale_id');
	}
}

创建 API 类

<?php namespace Api\Controllers;

use Ratiw\Api\BaseApiController;

class ClientsController extends BaseApiController
{
	protected $model = 'Entities\Clients\Client';
}

创建转换器类(可选)

这虽然是可选的,但如果您不想转换任何字段,则不需要创建转换器。

<?php namespace Api\Transformers;

use Ratiw\Api\BaseTransformer;

class ClientTransformer extends BaseTransformer
{
	public function transform($client)
	{
		return [
			'id' => (int) $client->id,
			'short_name' => $client->shortname,
			'full_name' => $client->name,
			'sale_id' => $client->sale_id,
			'contact' => $client->contact,
			'email' => $client->email,
			'phone' => $client->phone
		];
	}
}

####创建端点的路由

Route::group(['prefix' => 'api'], function()
{
    Route::get('clients/{id}', 'Api\Controllers\ClientsController@show');
    Route::get('clients', 'Api\Controllers\ClientsController@index');
    ...
}

附加信息

####默认路由此 API 包默认提供两种方法

  • index() 用于查询集合
  • show() 用于查询特定项

您应该能够通过浏览器测试它。只需转到 https://https://:8000 或您开发环境中适当的任何位置。但是,如果您已设置与这些不同的环境,您将需要为该环境创建一个配置文件。

注意:如果您使用 Google Chrome 浏览器,可以从 Chrome Web Store 安装 JSONView,以帮助美化 JSON 结果。

####允许域配置API类默认将首先检查调用方是否来自允许的主机或域名。如果它来自除配置之外的其他域名,将返回错误。

默认情况下,允许的主机如下

  • localhost
  • localhost:8000

为了更改此设置或添加更多主机,您需要在 app/config 目录中创建一个配置文件,如下所示

// app/config/api.php

<?php

return [
    'allow_hosts' => [
        'localhost:8000',
        'localhost'
        'myawesome.app:8000',  //<-- your addition allowable domain
    ],

    'allow_paths' => [
        'api/*'
    ]	
];

####排序操作可以通过在调用 API 控制器时在查询字符串中传递 sort 参数来进行排序操作。

https://:8000/clients?sort=shortname

要按降序排序,只需在排序列前面加上 -

https://:8000/clients?sort=-shortname

####过滤结果可以通过在查询字符串中指定 q 参数来过滤结果。

https://:8000/clients?q=John

默认情况下,它将在名为 code 的字段上执行 where 子句,如果您的模型没有 code 字段,这将导致错误。您可以像这样覆盖 search() 方法来修复此问题。

	...
	protected function search($query, $q)
	{
		return $query->where('shortname', 'like', "%$q%")
			->orWhere('name', 'like', '%$q%');
	}
	...

####指定默认过滤器如果您希望始终将特定条件应用于查询结果,可以通过覆盖 getDefaultFilters 函数来实现。此函数将传递 query builder 对象,您可以在其中应用任何条件。

class ClientsController extends BaseApiController
{
	...
    public function getDefaultFilters($query)
    {
        return $query->where('sale_id', Auth::id());
    }
	...
}

####分页结果 默认情况下,返回或转换的结果以每页10条记录进行分页。要更改此设置,只需在查询字符串中传递per_page参数。

https://:8000/clients?per_page=20

####限制返回的字段 您可以通过在查询字符串中提供fields参数来限制要返回的字段,如下所示。

https://:8000/clients?fields=id,name

####懒加载结果 要懒加载数据库查询的结果,只需在Api类的$eagerLoads数组属性中指定即可。

...
class ClientsController extends BaseApiController
{
	$protected $eagerLoads = ['saleRep'];
	...
}

####指定转换器类 API包将根据以下标准自动查找相应的转换器类

  • 使用指定在$transformer属性中的转换器类。如果转换器不存在,则会抛出异常。
  • 使用指定在$model属性中的$model的基本名称来猜测转换器类。如果转换器类不存在,则将使用Ratiw\Api\BaseTransformer类。

这提供了足够的便利和灵活性。如果您的项目较小且不是很复杂,您可以将Api类和转换器类放在同一个目录下。或者,如果您不需要转换任何内容,甚至不需要为Api类定义任何转换器。

但如果您的项目相当复杂或您更喜欢将事物放在可以整洁组织事物的目录中,您可以通过指定Api类中要使用的$transformer类来实现这一灵活性。

...
class ClientsController extends BaseApiController
{
	protected $model = 'Entities\Clients\Client';

	protected $transformer = 'Api\Transformers\ClientTransformer';
	...
}
...

####覆盖转换器路径 默认情况下,Api类将在同一目录中查找其相关的转换器类,但您可以通过在app/config/api.php文件中放置transformer_path来覆盖此设置。

<?php
return [
	'allowable_path' => [...];
	...
	'transformer_path' => 'Api\\Transfomers\\';
];

注意路径中的双反斜杠\\。尽管如此,路径末尾的双反斜杠是不必要的。

####转换器中的嵌入式资源 使用Fractal定义的机制可以包含嵌入式资源(嵌套资源)。

...
class ClientTransformer extends BaseTransformer
{
	protected $defaultIncludes = ['saleRep'];

	public function transform($client)
	{
		...
	}

    public function includeSaleRep($client)
    {
        $saleRep = $client->saleRep;

        return $this->item($saleRep, new SaleTransformer);
    }

}