我开始使用silex开发rest api。 这是我的第一个api! p>
我做了什么: strong> p>
更新: strong> \ nCode用Federic的提示进行了改进。 添加使用Symfony JsonResponse。 暂时不工作。 p>
它返回什么? p>
如何使用
<?php
require_once __DIR __。'/ vendor / autoload.php';
use Symfony \ Component \ HttpFoundation \ JsonResponse;
// init Silex app
$ app = new Silex \ Application();
$ app ['debug'] = true;
//配置数据库连接
$ app-> register(new Silex \ Provider \ DoctrineServiceProvider(),array(
'db.options'=> array(
'driver'=>'pdo_mysql',
'host'=>'127.0.0.1',
'dbname'=>'db',
'用户'=>'root',
'密码'=>'',
'charset'=>'utf8',
),\ n));
$ app-> get('/ apps',function()use($ app){
$ sql =“select apps.id,apps.guid,apps.title,clients。 apps.id_country = countries.id上的apps
内部联接国家/地区的客户端,countries.country,langs.lang,apps.active客户端上的客户端.id = apps.id_client
内部联接langs上的联接客户端 = apps.id_lang
按apps.created_at desc排序“;
$ results = $ app ['db'] - > fetchAll($ sql);
$ response ['status'] = array(
'code'=> 200,
'message'=> '确定'
);
$ response ['data'] = $ results;
//返回$ app-> json($ response);
$ jsonResponse = new JsonResponse($ response) );
$ jsonResponse-> setEncodingOptions(JsonReponse :: DEFAULT_ENCODING_OPTIONS | JSON_PRETTY_PRINT);
返回$ jsonResponse;
});
$ app-> run();
< / code> pre>
{“status”:{“code”:200,“message”:“OK “},”data“:[{”id“:”2“,”guid“:”a8559e9b-d850-4964-b672-335a87fe9e8b“,”title“:”Coverdine Plus Light“,”client“:”Servier“ “国”: “英格兰”, “郎”: “英语”, “积极”: “1”},{ “ID”: “1”, “GUID”: “4f242e9d-c041-4c79-bc82-b62604de403c” “标题”: “Coverdine”, “客户端”: “施维雅”, “国”: “英国”, “朗”: “英语”, “活性”: “0”}]}
代码> < / pre>
JSON_PRETTY_PRINT code>来改善人类对json对象的读取? p>
div>