cdyweb / trucker
一个简单的PHP实现的主动资源,用于消费任何REST API
Requires
- php: >=5.4.0
- doctrine/inflector: 1.0
- guzzle/guzzle: 3.8.1
- illuminate/config: ~4
- illuminate/container: ~4
- illuminate/support: ~4
- patchwork/utf8: 1.1.*
Requires (Dev)
- hot/phpunit-runner: dev-master
- mockery/mockery: 0.9.*
- phpunit/phpunit: 4.1.*
- satooshi/php-coveralls: dev-master
This package is not auto-updated.
Last update: 2024-10-02 08:35:14 UTC
README
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.json文件中的require
块来通过Composer安装库
"indatus/trucker": "dev-master"
接下来运行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'
现在您应该可以开始了。
### Configure outside LaravelIf your using Trucker outside Laravel you just need to create the .trucker
folder in your project root and copy the package's config files there. Here's the *nix command for that.
mkdir .trucker && cp vendor/indatus/trucker/src/config/* .trucker/
## Configuration Options Trucker comes with its own configuration file where you can specify options that are constant to your configuration.
### Auth (auth.php)### Error Handler (error_handler.php)Supported Option Details:
### Query Condition (query_condition.php)Supported Option Details:
When making a request for a collection you may specify conditions similar to a SQL WHERE clause. These will be sent along with your request as an array parameter which contains a grouping of key / values that define the set of conditions.
Supported Option Details:
The resulting GET parameters may look something like:
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 (request.php) ### Resource (resource.php) ### Response (response.php)Supported Option Details:
Wildcards may be used to match what an http code starts with (e.g - 20*
).
### Result Order (result_order.php)Supported Option Details:
### Transporter (transporter.php) ## Creating an entitySupported Option Details:
Now you can create an entity object for a noun in your API (this is the minimum code you'll need to get started):
<?php class Product extends Trucker\Resource\Model { }
Trucker uses convention over configuration, so it will infer what the URI should be based on your class name. In the example of 'Product' the URI will be assumed to be /products.
## Working with your entityNow that you have Trucker object you can use it with CRUD operations as you may expect you would with an ORM.
### Fetching RecordsTrucker splits fetching records over your API into 2 categories. Getting an instance and getting a collection.
#### Fetch an InstanceIf you have an entity where you know the value of it's identity_property
you can fetch it with the find()
method.
$p = Product::find(1);
Optional 2nd arg:
find()
takes a second parameter as well that allows you to pass in an arbitrary associative array that you want to be converted into query string arguments that get sent with the request.
#### Fetch a CollectionOptional 3rd arg:
find()
takes a third parameter as well that allows you to pass in an object of the class your finding on with properties that have been set at runtime. Thefind()
function will use this object for interperting the URL if given, other wise it will callnew static;
on the classfind()
is called on.
When you want to fetch a collection of records you can use the all()
function.
$results = Product::all();
The all()
function takes arguments that allow you to specify conditions on the results that you'll get back. How the request will be made to the API depends on collection_query_condition_driver
and collection_result_order_driver
you are using.
$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);
### Create, Update & Destroy Operations #### CreateNote: You may also provide a third array parameter to the
all()
function containing an associative array of values to include in the request as querystring parameters.
$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'] }#### Update
Update works quite similar to the create functionality, from the code perspective it is nearly identicial.
$p = Product::find(1); $p->name = "My Product"; if ($p->save()) { echo "Updated!"; } else { echo "Error: ". implode(", ", $p->errors()); }#### Destroy
The destroy function requires an existing instance, and returns a boolen based on the success of the request.
$p = Product::find(1); if ($p->destroy()){ echo "Deleted product: {$p->name}"; } else { echo "Error deleting product: {$p->name}"; echo "Errors: ". implode(", ", $p->errors()); }## Customizing Entities
Trucker uses sensible defaults for its default configuration, but allows you to customize it via the config settings. Additionally you can override the config settings for an individual class by overriding properties on the concrete implementation; by setting values at runtime on the class or in the config.
### Setting concrete class properties.The following fields can be set on a class implementation to override interpreted values, default values or just to define the class functionality.
Example:
<?php class Product extends Trucker\Resource\Model { protected $uri = "/small_electronic_products"; protected $guarded = "price,sale_price"; protected $fileFields = "picture"; }### Setting runtime properties
There may be situations where you can't set a property in the concrete class implementation because it's value is variable and changes at runtime. For this situation you could set the property before it is used in a request.
Example:
<?php $vendor_id = 9876; $p = new Product; $p->nestedUnder = "Vendor:{$vendor_id}"; $found = Product::find(1, [], $p); //will hit /vendors/9876/products/1### Setting config values at runtime
There may be times where you need to change values that are set in your Trucker config files at runtime before a request is made that uses those values. You can use Trucker's config manager for this.
注意:如果您在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);