delolmo/valinor-http-message

此包最新版本(1.7.1)没有提供许可信息。

使用psr/http-message作为Valinor的源

1.7.1 2023-11-17 08:40 UTC

This package is auto-updated.

Last update: 2024-09-15 17:51:36 UTC


README

以下库允许使用psr/http-message库的ServerRequestInterface对象作为cuyz/valinor库的源。

安装

composer require delolmo/valinor-http-message

示例

use App\DTO\CustomObject;
use CuyZ\Valinor\Mapper\Source\Source;
use CuyZ\Valinor\MapperBuilder;
use DelOlmo\Valinor\Mapping\Source\ServerRequestSource;
use Psr\Http\Message\ServerRequestInterface;

final class CustomController
{
    public function execute(ServerRequestInterface $request)
    {
        // Create the Source using the new InputSource
        $source = Source::iterable(new ServerRequestSource($input));
        
        // Create the Mapper, using the desired configuration
        $mapper = new MapperBuilder())
            ->allowSuperfluousKeys()
            ->enableFlexibleCasting()
            ->mapper();
            
        // Map the source to whatever object makes sense
        $mapped = $mapper->map(CustomObject::class, $source);
        
        // Apply whatever business logic makes sense from here
        // ...
    }
}

最后注意事项

  • delolmo/valinor-http-message的版本将始终与cuyz/valinor版本匹配。同样适用于PHP版本。
  • 虽然查询参数和请求体参数不应该具有相同的名称,但应注意,从ServerRequestSource的角度来看,查询参数始终优先于请求体参数。也就是说,如果存在具有相同名称的查询参数和请求体参数,ServerRequestSource将仅使用查询参数的值进行映射。
  • 考虑到许多查询和请求体参数被检索为字符串或数组,值得注意的是,应该在Mapper中配置enableFlexibleCasting。有关更多信息,请参阅启用灵活转换