needcaffeine / slim-api-extras
此软件包已被废弃,不再维护。未建议替代软件包。
这是一个为Slim框架添加RESTful功能的库
1.0.0
2014-05-22 14:34 UTC
Requires
- php: >=5.4.0
- slim/slim: >=2.4.2
This package is not auto-updated.
Last update: 2020-08-21 18:44:22 UTC
README
Slim API Extras
此库是Slim框架的扩展,允许轻松实现带有RESTful响应的API。
入门
安装
建议您通过Composer安装此软件包。
$ composer require needcaffeine/slim-api-extras
使用方法
<?php require 'vendor/autoload.php'; use \Needcaffeine\Slim\Extras\Views\ApiView; use \Needcaffeine\Slim\Extras\Middleware\ApiMiddleware; // This would probably be loaded from a config file perhaps. $config = array( 'slim' => array( 'debug' => true ) ); // Get the debug value from the config. $debug = $config['slim']['debug']; $app = new \Slim\Slim($config['slim']); $app->view(new ApiView($debug)); $app->add(new ApiMiddleware($debug)); // Example method demonstrating notifications // and non-200 HTTP response. $app->get('/hello', function () use ($app) { $request = $app->request(); $name = $request->get('name'); if ($name) { $response = "Hello, {$name}!"; $data = array("Red" => "dog", "Brown" => "dog"); $response['data'] = $data; } else { $response = array(); $response['notifications'][] = 'Name not provided.'; $responseCode = 400; } $responseCode = $responseCode ?: 200; $app->render($responseCode, $response); }); // Run the Slim application. $app->run();
响应示例
» curl -i "https:///hello" HTTP/1.1 400 Bad Request Content-Type: application/json; charset=utf-8 { "notifications": "Name not provided.", "meta": { "result": "failure", "status": 400 } } » curl -i "https:///hello?name=Vic" HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 { "notifications": "Hello, Vic!", "data": { "Red": "dog", "Brown": "dog" }, "meta": { "result": "success", "status": 200 } }