studiow/league-route-conversionstrategy

league/route 的智能转换策略

dev-master 2018-09-24 07:22 UTC

This package is auto-updated.

Last update: 2024-09-24 21:05:54 UTC


README

league/route 的智能转换策略。它允许您从控制器/处理程序返回几乎任何您想要的东西。

注意 该策略提供了一种方便的方法将多种类型的返回值转换为 ResponseInterface 对象。当然,您仍然可以返回 ResponseInterface 对象以获得最大控制。

安装

推荐使用 composer 安装此包

composer require studiow/league-route-conversionstrategy

在您的代码中使用它,就像使用任何其他 StrategyInterface 一样

$router = new \League\Route\Router();
$strategy = new \Studiow\LeagueRoute\Strategy\ConversionStrategy(
    new \Studiow\LeagueRoute\Strategy\Convertor\HtmlConvertor($responseFactory)
);
$router->setStrategy($strategy);

转换

该包捆绑以下转换

HtmlConvertor

此转换器将任何文本转换为 text/html 响应

$router = new \League\Route\Router();
$strategy = new \Studiow\LeagueRoute\Strategy\ConversionStrategy(
    new \Studiow\LeagueRoute\Strategy\Convertor\HtmlConvertor($responseFactory)
);
$router->setStrategy($strategy);

//we can now return text
$router->get('/text', function(){
    return 'Hello world';
});

JsonConvertor

此转换器将任何数组或对象转换为 application/json 响应

$router = new \League\Route\Router();
$strategy = new \Studiow\LeagueRoute\Strategy\ConversionStrategy(
    new \Studiow\LeagueRoute\Strategy\Convertor\JsonConvertor($responseFactory)
);
$router->setStrategy($strategy);

//we can now return arrays
$router->get('/array', function(){
    return ['foo'=>'bar'];
});

//or objects (that may or may not implement JsonSerializable
$router->get('/object', function(){
     return new ArrayObject(['foo'=>'bar']);
});

ConvertorCollection

此转换器允许您有多个转换。将使用第一个可用的转换

$router = new \League\Route\Router();

$convertors = new \Studiow\LeagueRoute\Strategy\Convertor\ConvertorCollection([
   new \Studiow\LeagueRoute\Strategy\Convertor\JsonConvertor($responseFactory),
   new \Studiow\LeagueRoute\Strategy\Convertor\HtmlConvertor($responseFactory)
]);

$strategy = new \Studiow\LeagueRoute\Strategy\ConversionStrategy($convertors);
$router->setStrategy($strategy);

//this will be handled by the HtmlConvertor
$router->get('/text', function () {
   return 'Hello world';
});

//this will be handled by the JsonConvertor
$router->get('/array', function () {
   return ['foo' => 'bar'];
});

//this will also be handled by the JsonConvertor
$router->get('/object', function () {
   return new ArrayObject(['foo' => 'bar']);
});

//you can always still return a ResponseInterface object. This will be unmodified:
$router->get('/full-response', function () {
   return new Response(...)
});