indatus/active-resource

一个简单的PHP编写的活动资源实现,用于消费任何REST API

dev-master 2014-02-17 21:21 UTC

This package is not auto-updated.

Last update: 2024-09-23 14:49:33 UTC


README

此包已被官方弃用,请参阅Trucker,这是替代品。

PHP ActiveResource 库

Build Status

这是一个用于以ActiveResource样式编码访问REST API的PHP库。好处是在快速且干净的编程接口中更容易使用REST API。

该库遵循约定优于配置。因此,您应该能够在很短的时间内快速掌握消费REST API。

安装

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

"indatus/active-resource": "dev-master"

然后运行composer updatecomposer install

示例

基本类

创建一个基类可能是个好主意,您的模型将从这个基类扩展,其中包含将在所有内容中共享的设置。

<?php

class ActiveResourceBase extends ActiveResource
{

	//add any global AR configs here

    public function __construct($attributes = array())
    {
        parent::__construct($attributes);
    }
}

ActiveResourceBase::$baseUri = "http://example.com";

现在创建一个实体(这是您需要的最小代码)

<?php

class Product extends ActiveResourceBase
{
    
}

该库使用约定优于配置,因此它将根据您的类名推断出URI。在“Product”的示例中,URI将被假设为/products

CRUD 操作

现在您有了ActiveResource类,您可以像预期使用ORM一样使用它进行CRUD操作。

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

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

您可以做什么?以下是一些基本操作

//find by id
$product = Product::find(1);

//update an attribute
$product->attribute = 'foo';

//update several attributes
$product->updateAttributes(array('name' => 'test', 'description' => 'some desc'));

//save the instance
$product->save(); //returns boolean

//get any errors from an invalid save
$product->errors();

//----------

//create a new object;
$product = new Product(array('name' => 'test', 'description' => 'some desc'));
$product->save();

//destroy an object;
$product->destroy();

//----------

//Find all with conditions

$conditions = array();
$conditions[] = array(
    Product::$searchProperty => 'some_property_1',
    Product::$searchOperator => '=',
    Product::$searchValue => 'value'
);

$conditions[] = array(
    Product::$searchProperty => 'some_property_2',
    Product::$searchOperator => '>=',
    Product::$searchValue => '123'
);

$conditions[] = array(
    Product::$searchProperty => 'some_property_3',
    Product::$searchOperator => 'LIKE',
    Product::$searchValue => '%partial name'
);

$collection = Product::findAll(
	$conditions,
	Product::$searchOperatorAnd,
	'some_property_1',
	Product::$orderDirDesc
);

请记住,该库使用约定优于配置,因此如果您想覆盖某些内容,您可能只需要设置受保护的属性。

例如,在Product上,URI将被推断为/products。就像Person将变为/people一样。如果您想使用不同的名称,您可以通过两种方式做到这一点。比如说,您想使Product使用/my_cool_products。您可以通过设置受保护的静态变量$resourceName为'MyCoolProduct'来实现,或者您可以简单地设置受保护的静态变量$uri/my_cool_products;

文档

请注意,此README是一个正在进行中的工作,希望可以添加更多示例,以展示该库的灵活性和您可以用它做什么。在此之前,请参阅doc*目录中的生成文档。