calebdre/api-sugar

一个使创建API更简单的库

dev-master 2016-01-05 10:51 UTC

This package is not auto-updated.

Last update: 2024-09-28 18:58:34 UTC


README

一个允许快速轻松创建API的库

此库使用 FlightEloquent 进行路由和数据库交互。
除了设置外,您不需要查看Flight的API,但如果您不熟悉Eloquent,请查看Eloquent文档。 在此处找到

用法

设置服务器路由

首先,您需要确保所有URL都重定向到您的index.php文件。

对于 Apache,使用以下内容编辑您的 .htaccess 文件

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

对于 Nginx,将以下内容添加到服务器声明中

server {
    location / {
        try_files $uri $uri/ /index.php;
    }
}

通过composer包含项目

运行 composer require calebdre/api-sugar

创建端点类

创建一个包含API端点和方法的类

class UserController extends ApiController{

    public $mappings = [
        'crud' => ['model' => 'Namespace\To\Model', 'resource_name' => 'users'],
	'fetchComment' => ['method' => 'get', 'route' => '/users/comment/@id'
    ];

    public function fetchComment($id){
	// do fetch comment stuff 
    }
}

让我们分解一下类
class UserController extends ApiController
所有端点类都需要继承ApiController类。

$mappings
这是一个可以添加以创建API端点的数组。结构如下
'methodName' => ['method' => 'get/post/put/delete', 'route' => '/end/point/path']
方法名是当路由被访问时应该调用的类中方法的名称。

您还可以向数组中传递 crud 以为Eloquent模型建立CRUD路由。其语法如下
'crud' => ['model' => 'namespace/to/model/class', 'resource_name' => 'nameOfRoutePrefix']

实例化API对象并配置数据库

	$api = new Api();
	$api->configureDB([
	    'driver'    => 'driver',
	    'host'      => 'host',
	    'database'  => 'database',
	    'username'  => 'username',
	    'password'  => 'pass',
	    'charset'   => 'utf8',
	    'collation' => 'utf8_unicode_ci',
	    'prefix'    => '',
	]);

	$api->addClass(new UserController());
	$api->execute();

您可以使用 addClass 方法添加您刚刚创建的类。要激活API,请使用末尾的 execute 方法。
您还可以使用 addEndPoint($methodType, $routeName, Callable $callable) 函数手动添加路由。

之后,您应该一切就绪!

关于返回JSON的说明

为了在方法中返回JSON,请确保使用 Flight::json($array) 创建JSON响应。 不要使用RETURN。

请随时为此项目做出贡献!