2011-10-21 54 views
0

我正在設計使用Slim框架的REST API。我正在使用數據庫mySql。我正在用PHP設計這個API。使用REST API從表中提取數據

我想從我的表中獲取有關學生的數據。

我想是這樣的: -

<?php 
header('Content-type: application/json'); 
// Include the Slim library 
require 'Slim/Slim.php'; 
// Instantiate the Slim class 
$app = new Slim(); 
// Create a GET-based route 
$app->get('/hello/:name', 'hello'); 

    function hello($name) 
    { 
    // here is code to access detail of $name 
    echo $name 
    // how can i get detail if i have value of name=:kuntal not name=kuntal 
    } 

    // Ready the routes and run the application 
    $app->run(); 
?> 

我使用這個網址嘗試這一功能: - 192.168.1.101/hello/:kuntal

我需要得到名稱的價值kuntal但在函數中,我得到的名字的價值爲:kuntal所以請告訴我如何刪除名稱前的(冒號)。

是另一種方法來做到這一點。

如果您意識到構建REST API的苗條框架,請給我您的建議。 預先感謝您。

回答

0

試試這個網址:192.168.1.101/hello/kuntal 我認爲這肯定會適用於您的代碼。

0

Slim是一個非常棒的框架。在我開始使用它之前,我沒有使用框架,REST,瞭解HTTP ......我仍然是一個noob,但Slim使它變得有趣。

答1:

$app->get('/hello/:name', function($name) use ($app) { 
    // Your mySQL code here 
    // Process that information into output JSON? 
    // echo json_encode($array); 
}); 

答2:

也許我補充一點,你看看Idiorm/Paris爲你的數據庫的需求?在與Slim相同的理念中,少就是更多。這是巴黎的代碼。

class Friend extends Model {} 

$app->get('/hello/:name', function($name) use ($app) { 

    $friend = Model::factory('Friend')->find_many($name); // Paris: all rows with name 
    $friendAry = $friend->as_array('id', 'name'); 

    $response = $app->response(); // Slim Response object at work 
    $response['Content-Type'] = 'application/json'; 

    echo json_encode($friendAry); // Output 
}); 

雖然,問題(也許有人知道更多關於REST可以回答)。這個Uri真的很好嗎?根據我對REST的瞭解,我們希望將人們指向資源。名詞我猜。我不確定Hello在REST環境中的真正含義。爲什麼不讓資源用戶或朋友使用ID作爲一個子彈?

$app->get('/friend/:id', function($id) use ($app) { 
    // Returns the friend with unique id 
    $friend = Model::factory('Friend')->find_one($id); // Name is already part of obj 
    $friendAry = $friend->as_array('id', 'name'); 
    echo json_encode($friendAry); 
} 

然後,您可以處理該信息,並用hello問候打包,無論客戶期待什麼。您可以將諸如name之類的額外信息傳遞給像這樣的參數。

http://search.twitter.com/search?q=potato&count=10

希望這有助於。非常酷的東西。有人給我反饋,讓我知道我的想法是否在正確的頁面上。我仍然在學習。