2016-04-06 56 views
1

我開始使用silex開發休息api。這是我的第一個API!使用Silex框架開發休息api

我做了什麼:

更新: 代碼Federic尖改善。添加使用Symfony JsonResponse。暫時不工作。

<?php 
require_once __DIR__.'/vendor/autoload.php'; 

use Symfony\Component\HttpFoundation\JsonResponse; 

// init Silex app 
$app = new Silex\Application(); 
$app['debug'] = true; 

//configure database connection 
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
    'db.options' => array(
     'driver' => 'pdo_mysql', 
     'host' => '127.0.0.1', 
     'dbname' => 'db', 
     'user' => 'root', 
     'password' => '', 
     'charset' => 'utf8', 
    ), 
)); 

$app->get('/apps', function() use ($app){ 
    $sql = "select apps.id, apps.guid, apps.title, clients.client, countries.country, langs.lang, apps.active from apps 
      inner join countries on apps.id_country = countries.id 
      inner join clients on clients.id = apps.id_client 
      inner join langs on langs.id = apps.id_lang 
      order by apps.created_at desc"; 
    $results = $app['db']->fetchAll($sql); 


     $response['status'] = array(
      'code' => 200, 
      'message' => 'OK' 
     ); 

     $response['data'] = $results; 

    //return $app->json($response); 
    $jsonResponse = new JsonResponse($response); 
    $jsonResponse->setEncodingOptions(JsonReponse::DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT); 

    return $jsonResponse; 
}); 


$app->run(); 

它返回什麼?

{"status":{"code":200,"message":"OK"},"data":[{"id":"2","guid":"a8559e9b-d850-4964-b672-335a87fe9e8b","title":"Coverdine Plus Light","client":"Servier","country":"England","lang":"English","active":"1"},{"id":"1","guid":"4f242e9d-c041-4c79-bc82-b62604de403c","title":"Coverdine","client":"Servier","country":"England","lang":"English","active":"0"}]} 

如何使用JSON_PRETTY_PRINT來改善人類閱讀我的json對象?

+0

而不是以漂亮的你的迴應,你應該使用像郵差的工具來測試您的API,它格式化爲了您的可讀性而提供的回覆。 – Maerlyn

+0

http://stackoverflow.com/questions/35142601/silex-app-json-returning-integer-data-as-strings/35161207#35161207 –

+0

Max P. - 感謝您的鏈接。它爲我工作。 –

回答

3

而不是使用$app->json($response);,而是使用JsonResponse。您可以用他的setEncodingOptions方法設置JSON_PRETTY_PRINT標誌。

<?php 
use Symfony\Component\HttpFoundation\JsonResponse; 

// ... 
$jsonResponse = new JsonResponse($response); 
$jsonResponse->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT); 

return $jsonResponse; 
+0

我試過這個解決方案,但它給了我這個錯誤:PHP致命錯誤:類'JsonReponse'找不到在 –

+0

你有沒有找到'使用Symfony \ Component \ HttpFoundation \ JsonResponse;'? – Federkun

0

我也有過這樣的困難,經過反覆研究,我發現功能:do_dump,click here看到它在github上。

要使用它,只是這樣做:



$var = json_decode('{"a":1,"b":2,"c":3,"d":4,"e":5}'); 
do_dump($var); 

2

這個工作對我來說:

... 
require_once(__DIR__ .'/../vendor/autoload.php'); 
use Symfony\Component\HttpFoundation\Response; 

... 
$response = $sth->fetchALL(PDO::FETCH_ASSOC); 
return $app->json($response, Response::HTTP_OK)->setEncodingOptions(JSON_PRETTY_PRINT);