PHP code example of zewail / think-api

1. Go to this page and download the library: Download zewail/think-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zewail / think-api example snippets


$api = new \Zewail\Api\Routing\Router;

$api->version('v1', function () {
	// TODO 可以是thinkphp自带的路由
});

use Zewail\Api\Facades\ApiRoute;

ApiRoute::version('v1', function(){
    // TODO 可以是thinkphp自带的路由
});

ApiRoute::version(['v1', 'v2'], function () {
	// TODO 可以是thinkphp自带的路由
});

ApiRoute::version('v1', function(){
    Route::rule('new/:id','index/News/read');
});

ApiRoute::version('v1', function () {
	Route::rule('new/:id','app\index\controller\V2\News@read');
  	// 或者
  	Route::rule('new/:id','index/V2.News/read');
});

ApiRoute::version('v2', function () {
    Route::rule('new/:id','app\index\controller\V2\News@read');
});

namespace app\index\controller;

use think\Controller;
use Zewail\Api\Api;

class BaseController extends Controller
{
	use Api;
}

namespace app\index\controller;

use Zewail\Api\Facades\Response as ApiResponse;

class IndexController
{
	public function index() {
        return ApiResponse::array([]);
    }
}

// 简单的成功响应, 默认200状态码, 可以在第二个参数改变
// 使用 trait, 其他方法都可以使用该方法,下面都使用 Facade 演示
return $this->response->array($user->toArray());
// 使用 Facade
return ApiResponse::success('Success', 200);

$user = User::get($id);
return ApiResponse::array($user->toArray());

$user = User::get($id);
return ApiResponse::item($user);

$users = User::all();
return ApiResponse::collection($users);

$users = User::paginate(10);
return ApiResponse::paginator($users);

// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle'       => 'Zewail\Api\Exceptions\handleException',

return ApiResponse::BadRequest();

return ApiResponse::OK($data);

return ApiResponse::item($user)->addMeta('foo', 'bar');

return ApiResponse::item($user)->setMeta($meta);

return ApiResponse::item($user)->setCode(200);

// 提供两种设置方式
return ApiResponse::item($user)->addHeader('X-Foo', 'Bar');
return ApiResponse::item($user)->addHeader(['X-Foo' => 'Bar']);

return ApiResponse::item($user)->setLastModified($time);

return ApiResponse::item($user)->setETag($eTag);

return ApiResponse::item($user)->setExpires($time);

return ApiResponse::item($user)->setCacheControl($cache);

// 如查询出来的$user具有id, name, age, mobile等属性
// 在设置了第二个参数为['id', 'name', 'age']后,将会过滤其他属性,只返回给接口列出的属性
return ApiResponse::item($user, ['id', 'name', 'age']);
return ApiResponse::collection($users, ['id', 'name', 'age']);
return ApiResponse::paginator($users, ['id', 'name', 'age']);

// 只选择模型中的id、name、age属性
return ApiResponse::only(['id', 'name', 'age'])->item($user);
// 排除模型属性age
return ApiResponse::except(['age'])->item($user);
// 还可以一起使用, 选择id、name、age属性后排除age
return ApiResponse::only(['id', 'name', 'age'])->except(['age'])->item($user);

return [
  // 用户相关接口
  // 例如设置一些用户的相关接口资源
  'user.age' => ['id', 'name', 'age'],
  'user.mobile' => ['id', 'name', 'mobile'],
];

// 返回{'data': {'id':1, 'name': 'xiaoming', 'age': 20}}
return ApiResponse::item($user, 'user.age');
// 返回{'data': {'id':1, 'name': 'xiaoming', 'mobile': '13777777777'}}
return ApiResponse::item($user, 'user.mobile');

// 返回{'data': {'id':1, 'name': 'xiaoming', 'age': 20}}
return ApiResponse::only('user.age')->item($user);
// 返回{'data': {'id':1, 'name': 'xiaoming', 'mobile': '13777777777'}}
return ApiResponse::only('user.mobile')->item($user);

// 返回Array格式的数据
return ApiResponse::item($user)->serializer('Array');
// 返回DataArray格式的数据
return ApiResponse::item($user)->serializer('DataArray');

namespace app\index\controller;

use app\index\model\User;
use Zewail\Api\Facades\Response;
use Zewail\Api\Facades\JWT;
use Zewail\Api\Exceptions\JWTException;

class Authenticate
{
	public function authenticate()
	{
        // $credentials 可以从请求中获取
        $credentials = ['email'=>'[email protected]', 'password' => '123456'];
        $token = JWT::attempt($credentials);
	}
}

namespace app\index\model;

use think\Model;

class User extends Model
{
	public $jwtSub = 'mobile';
}

public $jwtPassword = 'strange_password';

public function jwtEncrypt($password)
{
 	// 只要返回你加密后的结果,会自动比对数据库字段
  	return md5(sha1($password));
}

$user = User::get(1);
$token = JWT::fromUser($user);

$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$payload = JWT::makePayload($customClaims);
$token = JWT::encode($payload);

Authorization: Bearer {token}

http://api.example.com/news?token={token}

$payload = JWT::resolveToken();
// ['foo' => 'bar', 'baz' => 'bob']

if ($user = JWT::authenticate()) {
    // todo
}

// 从请求中获取token
$token = JWT::getToken();

// todo

// 对token进行解码
$payload = JWT::decode($token);

retrun [
    //配置项
];

retrun [
  //配置项
  // 用户相关接口
  // 例如设置一些用户的相关接口资源
  'user.age' => ['id', 'name', 'age'],
  'user.mobile' => ['id', 'name', 'mobile'],
];

// 返回{'data': {'id':1, 'name': 'xiaoming', 'age': 20}}
return $this->response->item($user, 'user.age');
// 返回{'data': {'id':1, 'name': 'xiaoming', 'mobile': '13777777777'}}
return $this->response->item($user, 'user.mobile');

retrun [
    //配置项
];

'user' => app\index\model\User::class,