tbbc / rest-util
一些处理REST(ful) API特定方面的有用类。
v1.0.0
2014-05-28 12:31 UTC
Requires
- php: >=5.3.3
Requires (Dev)
- phpunit/phpunit: 3.*
This package is not auto-updated.
Last update: 2024-09-23 14:59:59 UTC
README
PHP的REST util库。
该库实现了一些有用的实用类,用于解决REST(ful) API中经常出现的问题(例如:错误处理)。
快速入门
目录
描述
PHP的Rest util实用库
安装
使用 Composer,只需运行 $ composer require tbbc/rest-util 即可安装该包或
{ "require": { "tbbc/rest-util": "dev-master" } }
使用
将异常转换为错误对象
1. 首先,您需要定义一个 ExceptionMapping,为了示例,我们使用 PHP,但还提供了一个 YamlLoader
// Exception mapping configuration $invalidArgumentExceptionMapping = new ExceptionMapping(array( 'exceptionClassName' => '\InvalidArgumentException', 'factory' => 'default', 'httpStatusCode' => 400, 'errorCode' => 400101, 'errorMessage' => null, 'errorExtendedMessage' => 'Extended message', 'errorMoreInfoUrl' => 'http://api.my.tld/doc/error/400101', ));
2. 将 ExceptionMapping 添加到 ExceptionMap
$exceptionMap = new ExceptionMap(); $exceptionMap->add($invalidArgumentExceptionMapping);
3. 将 ErrorResolver 与一个 ErrorFactory 连接,库中捆绑了一个 DefaultErrorFactory
// Error resolver initialization $errorResolver = new ErrorResolver($exceptionMap); $defaultErrorFactory = new DefaultErrorFactory(); $errorResolver->registerFactory($defaultErrorFactory);
4. 解决错误!
$exception = new \InvalidArgumentException('This is an invalid argument exception'); $error = $errorResolver->resolve($exception);
5. 现在,$error 变量被分配了一个实现了 toArray() 方法的 ErrorInterface 对象,这允许您轻松地以您选择的方式进行序列化
print_r($error->toArray()); /* will output Array ( [http_status_code] => 400 [code] => 400101 [message] => This is an invalid argument exception. [extended_message] => Extended message [more_info_url] => http://api.my.tld/doc/error/400101 ) */ echo json_encode($error->toArray()); /* And voilà! You get a ready to use json normalized error response body { "http_status_code": 400, "code": 400101, "message": "This is an invalid argument exception.", "extended_message": "Extended message", "more_info_url": "http:\/\/api.my.tld\/doc\/error\/400101" } */
有关更具体的实际使用示例,请参阅我们将库集成到Symfony应用程序的扩展包:TbbcRestUtilBundle。
运行测试
首先确保您已安装所有依赖项,运行
$ composer install --dev
然后,从根目录运行测试
$ vendor/bin/phpunit
贡献
- 查看问题列表。
- 分支
- 编写测试(针对新功能或错误)
- 提交PR
需求
- PHP 5.3+
作者
- Boris Guéry - guery.b@gmail.com - http://borisguery.com
- Benjamin Dulau - benjamin.dulau@gmail.com
许可
The Big Brains Company - Rest Util 在MIT许可下授权 - 请参阅LICENSE文件以获取详细信息