3

この Cakephp CookBook に従って、RESTful api の簡単なセットアップ:

HTTP Method     URL.method  Controller action invoked
GET     /recipes*.method*   RecipesController::index()
GET     /recipes/123.method     RecipesController::view(123)
POST    /recipes*.method*   RecipesController::add()
PUT     /recipes/123*.method*   RecipesController::edit(123)
DELETE  /recipes/123.method     RecipesController::delete(123)
POST    /recipes/123*.method*   RecipesController::edit(123)

ここでは、すべての URL パラメータは数値、つまり 123 です。

GET     /recipes/test.json  RecipesController::view(123)

これは私にエラーを与えます:

{
   code: "404"
   url: "/myproject/recipes/test.json"
   name: "Action RecipesController::test() could not be found."
}

ここにURL

     "/myproject/recipes/test.json" // doesn't work

but 
      "/myproject/recipes/123.json" // works 

私はデフォルトを使用しましたRouter::mapResources('recipes')

前もって感謝します!

4

2 に答える 2

6

そのコードの APIを読み取ると、ドットの前に渡された値が自動的にidorに一致しますUUID。そのAPIにはparams定義があります

'id' - ID の照合時に使用する正規表現フラグメント。デフォルトでは、整数値と UUID に一致します。

何をするかは、いくつかの事前に確立されたオプション(基本的には:controller/:action/:idmapResourcesの形式を持っています)で多くを追加するだけです。Router::connect

したがって、ルールが ID (cake は int と見なす) を正規表現に一致させることである場合、文字列がその検証に合格していないことは明らかです。したがって、Routerはそのルールをスキップしてconnect、一方が一致するまで他方に進みます。そして、一致するのは:controller/:action.extensionの形式です(おそらく)。そのため、そのエラーが発生していますが、test明らかにアクションを意図したものではありません。

幸いなことに、mapResourcesカスタマイズに使用できるオプションの 1 つは、$id.

文字列のオプションを「id」として追加するには (接続ルートを で追加した場合に REST アクションが受け取る唯一の変数であるためmapResources)、そのルールを検証する正規表現を次のように変更します。

Router::mapResources('recipes', array('id'=>'[0-9A-Za-z]'));

またはあなたが作りたいどんなルールでも(私は正規表現が苦手なので、必要なものに調整してみてください)。

APIのドキュメントを見て、他に追加できるオプションを確認してください。

あなたの人生を楽にするためにそこにあることを覚えておいてくださいmapResources。したがって、より多くのパラメーターまたは何か追加のより複雑なルートが必要な場合は、ルートを忘れてmapResources自分で構築することを検討してください(提供したリンクのページの下部にあるように) .

于 2013-06-18T19:14:23.920 に答える
1

コードの下のルートで定義します。

// used for the rest API 
$routes->extensions(['json','xml']); // type of format you want to get response
$routes->resources('Api');

次に、コントローラーフォルダー内に以下のような API のコントローラーを作成します。

<?php
namespace App\Controller;
use Cake\I18n\Time;
use Cake\Database\Type; 
Type::build('date')->setLocaleFormat('yyyy-MM-dd'); // customize date format

// src/Controller/RecipesController.php
class ApiController extends AppController
{

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
        // load Model 
        $this->loadModel('Sales'); // load model to fetch data from database
        $this->Auth->allow();      // allow URL to public in case of Auth check 
    }

    public function beforeFilter(\Cake\Event\Event $event)
    {
        parent::beforeFilter($event);
        $this->loadComponent('RequestHandler');     
        $this->loadComponent('Flash');

    }

    public function index($fromdate = null, $todate = null)
    {
        //set date range to fetch the sales in particular date 
        if(!empty($_GET['fromdate_utc']) && !empty($_GET['todate_utc'])){
            // if from amd to date are same add +1 day in to date to get result 
            $to_date = date('Y-m-d', strtotime($_GET['todate_utc'] . ' +1 day'));
            $dateRage = array('Sales.SalesDate >= ' => $_GET['fromdate_utc'], 'Sales.SalesDate <=' => $to_date);
        }else{
            $dateRage = array();                    
        }

        $conditions = array(
            'and' => array($dateRage),
        );

        //$this->Auth->allow();
        $sales= $this->Sales->find('all', array(
                        'conditions' => $conditions
                    ))
                    ->select(['SalesNo', 'SalesDate', 'TotalValue', 'TotalDiscount', 'NetTotal', 'PaymentMode', 'Status'])
                    ->where(['StoreId' => '1']);
       // set data for view or response of API
        $this->set([
            'sales' => $sales,
            '_serialize' => ['sales']
        ]);
    }

}

?>

以下の XML 形式チェックの API URL でパラメーターを渡す方法:-

https://example.com/api/index.xml?fromdate_utc=2016-10-03&todate_utc=2016-10-03

以下の JSON 形式チェックの API URL でパラメーターを渡す方法:-

https://example.com/api/index.json?fromdate_utc=2016-10-03&todate_utc=2016-10-03
于 2016-11-21T09:49:16.460 に答える