这个在写app接口的时候很好用,更改一些默认配置项目即可,在项目配置文件或者公共配置文件里面配置:
'default_return_type' => 'json',
默认的响应类型是html
<?php
namespace app\api\controller;
use Timo\Core\App;
use model\user\UserModel;
class User extends Controller
{
public function profile()
{
$uid = Request::getInt('uid');
if ($uid <= 0) {
return App::result(1, 'params error');
}
//从UserModel获取用户数据
$userModel = new UserModel();
$user = $userModel->get($uid, 'uid, nickname, avatar');
return App::result(0, '获取成功', [
'user' => $user
]);
}
}
很简单吧,直接return一个数组就可以了,响应的就是json数据了
{
"code":0,
"msg":"获取成功",
"data":{
"user": {
"uid":100001,
"user_name":"Tommy",
"avatar":"http://www.timophp.com/static/avatar/00/00/01/83767494333.jpg"
}
}
}