簡體   English   中英

Kohana Rest API實施:如何從SupersonicAds / kohana-restful-api開始?

[英]Kohana rest api implementaion: how to start with SupersonicAds/kohana-restful-api?

我是kohana框架的新手。 我需要為我的應用程序實現rest api。 我從https://github.com/SupersonicAds/kohana-restful-api下載了rest api,並將其放置在我的本地主機中。 在模塊下。 現在文件結構是 在此處輸入圖片說明 我已經在bootstrap.php中啟用了模塊

Kohana::modules(array(
'auth'             => MODPATH.'auth',       // Basic authentication
'rest'              => MODPATH.'rest',    // Basic Rest example
// 'cache'      => MODPATH.'cache',      // Caching with multiple backends
// 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
 'database'   => MODPATH.'database',   // Database access
// 'image'      => MODPATH.'image',      // Image manipulation
// 'minion'     => MODPATH.'minion',     // CLI Tasks
 'orm'        => MODPATH.'orm',        // Object Relationship Mapping
// 'unittest'   => MODPATH.'unittest',   // Unit testing
// 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
));

我已經通過擴展“ Controller_Rest ”創建了一個控制器,現在根據Wiki,我應該能夠訪問“ $ this-> _ user,$ this-> _ auth_type和$ this-> _ auth_source ”變量,但是在我的情況下,它不會發生在我身上做錯了嗎? 而且我檢查了控制台網絡,它始終顯示狀態為“ 401未經授權”

要使用授權,您需要擴展Kohana_RestUser類

您使用的模塊帶有一個抽象的Kohana_RestUser類,您必須在應用程序中對其進行擴展。 需要實現的唯一函數是受保護的函數_find()。 該函數的實現有望基於API密鑰加載任何與用戶相關的數據。

我會舉例說明

<?php
// Model/RestUser.php
class RestUser extends Kohana_RestUser {
    protected $user='';
    protected function _find()
    {

    //generally these are stored in databases 
    $api_keys=array('abc','123','testkey');

    $users['abc']['name']='Harold Finch';
    $users['abc']['roles']=array('admin','login');

    $users['123']['name']='John Reese';
    $users['123']['roles']=array('login');

    $users['testkey']['name']='Fusco';
    $users['testkey']['roles']=array('login');

    foreach ($api_keys as $key => $value) {
        if($value==$this->_api_key){
            //the key is validated which is authorized key
            $this->_id = $key;//if this not null then controller thinks it is validated
            //$this->_id must be set if key is valid.
            //setting name
            $this->user = $users[$value];
            $this->_roles = $users[$value]['roles']; 
            break;

        }
    }


    }//end of _find
    public function get_user()
    {
        return $this->name;
    }
}//end of RestUser

現在測試控制器

<?php defined('SYSPATH') or die('No direct script access.');
//Controller/Test.php
class Controller_Test extends Controller_Rest
{
    protected $_rest;
    // saying the user must pass an API key.It is set according to the your requirement
    protected $_auth_type = RestUser::AUTH_TYPE_APIKEY;
    // saying the authorization data is expected to be found in the request's query parameters.
    protected $_auth_source = RestUser::AUTH_SOURCE_GET;//depends on requirement/coding style
    //note $this->_user is current Instance of RestUser Class

    public function before()
    {
        parent::before();
        //An extension of the base model class with user and ACL integration.
        $this->_rest = Model_RestAPI::factory('RestUserData', $this->_user);

    }
    //Get API Request
    public function action_index()
    {

        try
        {

                $user = $this->_user->get_name();
                if ($user)
                {
                    $this->rest_output( array(
                        'user'=>$user,

                    ) );
                }
                else
                {
                    return array(
                        'error'
                    );
                }
        }
        catch (Kohana_HTTP_Exception $khe)
        {
            $this->_error($khe);
            return;
        }
        catch (Kohana_Exception $e)
        {
            $this->_error('An internal error has occurred', 500);
            throw $e;
        }

    }
    //POST API Request
    public function action_create()
    {
        //logic to create 
        try
        {
            //create is a method in RestUserData Model
            $this->rest_output( $this->_rest->create( $this->_params ) );
        }
        catch (Kohana_HTTP_Exception $khe)
        {
            $this->_error($khe);
            return;
        }
        catch (Kohana_Exception $e)
        {
            $this->_error('An internal error has occurred', 500);
            throw $e;
        }
    }
    //PUT API Request
    public function action_update()
    {
        //logic to create
    }
    //DELETE API Request
    public function action_delete()
    {
        //logic to create
    }

}

現在RestUserData模型

<?php
//Model/RestUserData.php
class Model_RestUserData extends Model_RestAPI {

        public function create($params)
        {
            //logic to store data in db
            //You can access $this->_user here
        }

}

所以index.php / test?apiKey = abc返回

{
     "user": {
        "name": "Harold Finch",
        "roles": [
            "admin",
            "login"
        ]
    }
   }

注意:apiKey中的K為大寫/大寫

我希望這有助於快樂編碼:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM