專案

一般

個人檔案

動作

使用 PHP 的 REST API

php-redmine-api 專案

PHP ActiveResource 的使用方法

以下是一個使用 PHP ActiveResource 的範例,這是一個輕量級的 PHP 函式庫,可用於存取 Rails 的 REST API

<?php
require_once ('ActiveResource.php');

class Issue extends ActiveResource {
    var $site = 'http://username:password@192.168.199.129:3000/';
    var $request_format = 'xml'; // REQUIRED!
}

// create a new issue
$issue = new Issue (array ('subject' => 'XML REST API', 'project_id' => '1'));
$issue->save ();
echo $issue->id;

// find issues
$issues = $issue->find ('all');
for ($i=0; $i < count($issues); $i++) {
    echo $issues[$i]->subject;
}

// find and update an issue
$issue->find (1);
echo $issue->subject;
$issue->set ('subject', 'This is the new subject')->save ();
// update status
$issue->set ('status_id', 2)->save();

// delete an issue
$issue->find (1);
$issue->destroy ();
?>

已知問題

  • 如果您正在處理大量的描述,Web 伺服器可能會傳回 417 錯誤(錯誤的預期)。
    您應該將*ActiveResource.php*中的第 381 行替換為以下程式碼
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Expect:',"Content-Type: text/xml", "Length: " . strlen ($params)));
  • 如果您嘗試使用該類別來寫入「time_entries」,您將收到 404 回應(#9375)。原因是該類別無法從實體名稱的複數形式建立正確的單數形式。(2011 年 10 月 6 日編輯:根據網站,該錯誤已在最新版本中修復:https://github.com/lux/phpactiveresource/issues/7#issuecomment-2300502
    這可以在*ActiveResource.php*中透過以下方式修補
    1. 新增類別變數「$sOriginalElementName」
      protected $sOriginalElementName = '';
    2. 變更建構函式,以便在呼叫複數化之前使用原始實體名稱來設定類別變數
      function __construct ($data = array ()) {
        $this->_data = $data;
      
        // add this line here - to store the original name of the entity
        $this->sOriginalElementName = ($this->element_name ? $this->element_name : strtolower (get_class ($this)));
        // Allow class-defined element name or use class name if not defined
        $this->element_name = ($this->element_name ? $this->pleuralize ($this->element_name) : $this->pleuralize (strtolower (get_class ($this))));
      ...
      
    3. 然後變更「_send_and_receive」方法以使用「$sOriginalElementName」而不是「substr ($this->element_name, 0, -1)」
      function _send_and_receive ($url, $method, $data = array ()) {
        $params = '';
        $el = $this->sOriginalElementName;//substr ($this->element_name, 0, -1);
        if ($this->request_format == 'url') {
      ...
      

Kevin Saliou 於大約 11 年前更新 (2013 年 6 月 20 日) · 14 個版本