phpactiveresource/phpactiveresource

一个用于轻松访问基于 Ruby on Rails 的 REST 服务的 PHP 客户端库。

1.0.0-stable 2013-02-01 20:10 UTC

This package is auto-updated.

Last update: 2024-09-06 10:37:59 UTC


README

Click here to lend your support to: phpactiveresource and make a donation at www.pledgie.com !

这是一个 PHP 类,用于以 ActiveResource 编码风格访问 Ruby on Rails REST API。优点是更容易使用基于 RoR 的 REST 服务,而无需每次都手动创建基于 CURL 的客户端。希望这个类能节省一些人在 PHP 中编写针对 RoR 基于的 REST 服务的代码时间。这绝对不是一种详尽的移植,并且缺少一些方法,但它确实尝试涵盖所有基本功能。

注意:您需要在系统上安装 php curl 扩展。在 Ubuntu 上,您可以通过以下方式安装它

sudo apt-get install php5-curl

使用方法

使用 Composer

创建一个 composer.json 文件,内容如下

{
	"require": {
		"phpactiveresource/phpactiveresource": "dev-master"
	}
}

现在通过 Composer 的自动加载器加载脚本

<?php

require_once 'vendor/autoload.php';

use ActiveResource\ActiveResource;

class Song extends ActiveResource {
	public $site = 'http://localhost:3000/';
	public $element_name = 'songs';
}

// etc.

?>

不使用 Composer

<?php

require_once ('lib/ActiveResource.php');

class Song extends ActiveResource {
    var $site = 'http://localhost:3000/';
    var $element_name = 'songs';
}

// create a new item
$song = new Song (array ('artist' => 'Joe Cocker', 'title' => 'A Little Help From My Friends'));
$song->save ();

// fetch and update an item, chaining statements
$song->find (44)->set ('title', 'The River')->save ();

// fetch and update, line by line
$song->find (44);
$song->title = 'The River';
$song->save ();

// get all songs
$songs = $song->find ('all');

// delete a song
$song->find (44);
$song->destroy ();

// custom method
$songs = $song->get ('by_year', array ('year' => 1999));

?>

额外的 URL 参数

如果您想将额外的参数添加到 URL 的末尾,例如 API 密钥,您可以设置 $extra_params

<?php

require_once ('lib/ActiveResource.php');

class Song extends ActiveResource {
    var $site = 'http://localhost:3000/';
    var $element_name = 'songs';
    var $extra_params = '?key=123456789';
}

额外的 HTTP 头部

如果您需要添加额外的 HTTP 请求头部,您可以设置 $request_headers

<?php

require_once ('lib/ActiveResource.php');

class Song extends ActiveResource {
    var $site = 'http://localhost:3000/';
    var $element_name = 'songs';
    var $request_headers = array("x-api-key: some-api-key-here");
}

有关更多示例和文档,请参阅 GitHub Wiki 页面。