tripomatic/nette-api

使用 Nette 框架构建 REST API

dev-master / 1.0.x-dev 2016-05-02 14:50 UTC

This package is not auto-updated.

Last update: 2024-09-28 17:00:08 UTC


README

使用 Nette 框架 构建 REST API。

Tripomatic\NetteApi 是一个用于使用 Nette 框架构建 REST API 的非常轻量级的基础库。它提供了一个极其简约的 基础呈现器,一个 错误呈现器,确保在任何错误情况下返回有效的 JSON,并负责日志记录,还有一个方便的 JSON 格式化工具,可以在浏览器中测试 API 而不必隐藏您的 Tracy 面板。

安装

使用 Composer 安装 Tripomatic\NetteApi

$ composer require tripomatic/nette-api

快速入门

在您的 NEON 配置 中添加 Tripomatic\NetteApi 扩展

extensions:
  	api: Tripomatic\NetteApi\DI\ApiExtension

创建第一个继承自简约的 Tripomatic\NetteApi\Application\Presenter 的 RESTful 呈现器

use Nette\Application\Request;
use Tripomatic\NetteApi\Application\Presenter;
use Tripomatic\NetteApi\Application\Responses\JsonResponse;

class WeatherPresenter extends Presenter
{
	public function get(Request $request)
	{
		$city = $request->getParameter('city');

		$data = ...; // get weather data for the city
		return new JsonResponse($data);
	}

	// implement ohter REST methods similarly
}

配置

Tripomatic\NetteApi 不需要任何额外的配置,它设置了两个方便的默认值

  • 设置了错误呈现器,确保 API 在所有错误情况下返回有效的 JSON。
  • 默认情况下,在调试模式下运行时,API 响应将被格式化,Tracy 面板也将可见。

可以在相应的扩展部分的相应位置轻松覆盖此行为

api:
	prettify: %debugMode% # can be set to TRUE/FALSE
	errorPresenter: NetteApi:Error
	mapping:
		NetteApi: 'Tripomatic\NetteApi\Application\Presenters\*Presenter'

引导

如果您在编写应用程序引导时需要一些帮助,这里是一个我们在 Tripomatic 中使用的示例

require __DIR__ . '/../vendor/autoload.php';

$tomDebug = getenv('TOM_DEBUG') === 'TRUE' && isset($_COOKIE['tom_api_debug']);
$tomLogDir = getenv('TOM_LOG_DIR') ?: '/var/log/tripomatic/some-api';
$tomTmpDir = getenv('TOM_TMP_DIR') ?: '/var/tmp/some-api';
$tomConfigFile = getenv('TOM_CONFIG_FILE') ?: __DIR__ . '/../config/config.local.neon';

$configurator = new Nette\Configurator;
$configurator->setDebugMode($tomDebug);
$configurator->enableDebugger($tomLogDir);

$configurator->setTempDirectory($tomTmpDir);
$configurator->addConfig(__DIR__ . '/../config/config.neon');
if (file_exists($tomConfigFile)) {
	$configurator->addConfig($tomConfigFile);
}

return $configurator->createContainer();

是的,使用 Nette 框架,它真的可以是那么简约。其他所有事情都可以通过 Nette 的出色的 依赖注入实现 完成。有关更多详细信息,请参阅 Nette 框架文档

许可证

Tripomatic\NetteApi 在 MIT 许可证下授权。