indatus/trucker

一个简单的PHP实现,用于消费任何REST API

v1.0.2 2014-07-31 15:16 UTC

This package is not auto-updated.

Last update: 2024-09-23 06:41:03 UTC


README

Latest Stable Version Total Downloads Build Status Coverage Status Dependency Status

Trucker是一个PHP包,可以将远程API资源(通常是RESTful)映射为ActiveResource风格的模型。其优点是使远程API在快速且干净的编程接口中更容易使用。

<?php

class Product extends Trucker\Resource\Model {} //create a class to use

$p = new Product(['name' => 'My Test Product']);
$success = $p->save(); //create a new entity

$found = Product::find(1); //find an existing entity

$found->name = 'New Product Name';
$success = $found->save(); //update an entity

$success = $found->destroy(); //destroy an entity

$results = Product::all(); //find a collection

本项目正在寻找新的维护者。如有兴趣,请提交问题。

README内容

安装

需求

  • 任何PHP 5.4+版本都可以

使用Composer安装

您可以通过将以下行添加到composer.json文件的require块中,使用Composer安装库:

"indatus/trucker": "dev-master"

有关Laravel 5支持的信息,请参阅laravel-5分支

接下来运行composer install,现在您需要发布配置文件。

Trucker的配置文件是您定义与API交互的常量信息的地方,如端点、您想使用的驱动等。

Laravel中的配置

Trucker与Laravel框架配合良好。如果您在Laravel中使用Trucker,只需运行以下命令即可将Trucker配置文件发布到app/config/packages/indatus/trucker文件夹。

php artisan config:publish indatus/trucker

最后一步是添加服务提供者。打开app/config/app.php,并将新项目添加到提供者数组中。

'Trucker\TruckerServiceProvider'

现在您应该可以开始使用了。

Laravel之外配置

如果您在 Laravel 之外使用 Trucker,只需在项目根目录下创建 .trucker 文件夹,并将包的配置文件复制到那里即可。以下是相应的 *nix 命令。

mkdir .trucker && cp vendor/indatus/trucker/src/config/* .trucker/

配置选项

Trucker 内置自己的配置文件,您可以在其中指定配置中的常量选项。

认证(auth.php)

支持选项详情

错误处理器(error_handler.php)

支持选项详情

查询条件(query_condition.php)

在请求集合时,您可能需要指定类似于 SQL WHERE 子句的条件。这些条件将作为数组参数与您的请求一起发送,该参数包含一组键/值,用于定义条件集合。

支持选项详情

生成的 GET 参数可能如下所示

search[0][property]=someProperty
search[0][operator]=<
search[0][value]=1234
search[1][property]=anotherProperty
search[1][operator]=LIKE
search[1][value]=someString
logical_operator=AND

请求(request.php)

支持选项详情

资源(resource.php)

响应(response.php)

可以使用通配符来匹配以 http 状态码 开头 的内容(例如 - 20*)。

支持选项详情

结果排序(result_order.php)

支持选项详情

传输器(transporter.php)

创建实体

现在您可以为 API 中的名词创建实体对象(这是您开始所需的最少代码)

<?php
class Product extends Trucker\Resource\Model
{

}

Trucker 使用约定优于配置,因此它将根据您的类名推断出 URI 应该是什么。在“Product”示例中,URI 将假定是 /products

使用您的实体

现在您有了 Trucker 对象,您可以像使用 ORM 一样使用 CRUD 操作。

获取记录

Trucker 将通过您的 API 获取记录分为两大类:获取一个实例和获取一个集合。

获取一个实例

如果您有一个实体,您知道其 identity_property 的值,您可以使用 find() 方法来获取它。

$p = Product::find(1);

可选的第二个参数: find() 还接受一个第二个参数,允许您传递一个关联数组,该数组将被转换为查询字符串参数,随请求一起发送。

可选的第三个参数: find() 还接受一个第三个参数,允许您传递一个对象,该对象包含您正在查找的类的属性,这些属性在运行时已设置。如果提供该对象,则 find() 函数将使用该对象来解析 URL;否则,它将在调用 find() 的类上调用 new static;

获取一个集合

当您想要获取一组记录时,可以使用 all() 函数。

$results = Product::all();

all() 函数接受参数,允许您指定您将获取的结果的条件。对 API 的请求如何进行取决于您正在使用的 collection_query_condition_drivercollection_result_order_driver

使用查询条件和结果排序获取集合
$conditions = ConditionFactory::build();
$conditions->addCondition('name', '=', 'Roomba 650');
$conditions->addCondition('vendor', '=', 'Irobot');
$conditions->addCondition('price', '>=', 10000);
$conditions->setLogicalOperator($conditions->getLogicalOperatorAnd());

$order = ResultOrderFactory::build();
$order->setOrderByField('name');
$order->setOrderDirection($order->getOrderDirectionDescending());

$results = Product::all($conditions, $order);

注意:您还可以向 all() 函数提供一个包含作为查询字符串参数包含的值的关联数组的第三个数组参数。

创建、更新 & 销毁操作

创建

$attributes = ['name' => 'XYZ Headphones', 'vendor' => 'Acme', 'price' => '10000'];

//pass attributes to the constructor
$p = new Product($attributes);

//or use the fill() method
$p = new Product;
$p->fill($attributes);

//get the attributes back if you want to see them
print_r($p->attributes());
// => ['name' => 'XYZ Headphones', 'vendor' => 'Acme', 'price' => '10000']

//maybe you want to see a particular property
echo $p->name; // => XYZ Headphones

//or modify a property
$p->name = "ABC Headphones";

//save the object over the API.  The save() method will create or update 
//the object as necessary.  It returns true or false based on success.
$success = $p->save(); 

if ($success) {

  //the identity property is set back on the object after it is created
  echo "Saved product '{$p->name}' with ID: ". $p->getId();

} else {

  //maybe you want to print out the errors if there were some
  echo "Errors: ". implode(", ", $p->errors());
  // => ['Category is required', 'Cost must be greater than 0']
}

更新

更新功能与创建功能非常相似,从代码角度来看几乎相同。

$p = Product::find(1);
$p->name = "My Product";

if ($p->save()) {
   echo "Updated!";
} else {
   echo "Error: ". implode(", ", $p->errors());
}

销毁

销毁函数需要一个现有的实例,并根据请求的成功与否返回一个布尔值。

$p = Product::find(1);

if ($p->destroy()){
  echo "Deleted product: {$p->name}";
} else {
  echo "Error deleting product: {$p->name}";
  echo "Errors: ". implode(", ", $p->errors());
}

自定义实体

Trucker在默认配置中使用了合理的默认值,但允许您通过配置设置来自定义它。此外,您可以通过在具体实现上覆盖属性或在运行时在类或配置中设置值来覆盖单个类的配置设置。

设置具体类的属性。

以下字段可以在类实现中设置,以覆盖解释值、默认值或仅定义类功能。

示例

<?php
class Product extends Trucker\Resource\Model
{
  protected $uri = "/small_electronic_products";
  protected $guarded = "price,sale_price";
  protected $fileFields = "picture";
}

设置运行时属性

可能存在您无法在具体类实现中设置属性的情况,因为它的值是可变的,并且在运行时变化。对于这种情况,您可以在请求中使用该属性之前设置该属性。

示例

<?php
$vendor_id = 9876;
$p = new Product;
$p->nestedUnder = "Vendor:{$vendor_id}";
$found = Product::find(1, [], $p);
//will hit /vendors/9876/products/1

在运行时设置配置值

可能存在需要在请求之前在Trucker配置文件中更改值的场景,该请求使用了这些值。您可以使用Trucker的配置管理器来完成此操作。

注意:如果您在使用Laravel中的Trucker,您可能希望将Trucker配置管理器的别名Config更改为类似TruckerConfig的名称,以避免与Laravel自己的Config类冲突。

示例

<?php
use Trucker\Facades\Config as TruckerConfig;

TruckerConfig::set('auth.basic.username', $someUsername);
TruckerConfig::set('auth.basic.password', $somePassword);
$found = Product::find(1);