php - 使用Api-Platform,如何在创建时自动将授权用户添加为资源所有者?

标签 php symfony symfony4 api-platform.com

如何在创建时自动将当前授权用户添加到资源(POST)。

我正在使用 JWT 身份验证,并且/api/路由受到未经授权的用户的保护。我想设置它,以便在经过身份验证的用户创建新资源时(即通过向 POST 发送 /api/articles 请求)新创建的 Article资源与经过身份验证的用户有关。

我目前正在使用自定义 EventSubscriber每个资源类型从 token 存储中添加用户。

这是订阅者基类的要点:
https://gist.github.com/dsuurlant/5988f90e757b41454ce52050fd502273

以及扩展它的实体订阅者:
https://gist.github.com/dsuurlant/a8af7e6922679f45b818ec4ddad36286

但是,例如,如果实体构造函数需要用户作为参数,这将不起作用。

例如。

class Book {

    public User $owner;
    public string $name;

    public class __construct(User $user, string $name) {
        $this->owner = $user;
        $this->name  = $name;
    }
}

如何在实体创建时自动注入(inject)授权用户?

最佳答案

暂时我用的是DTOs and data transformers .

主要缺点是必须为需要此行为的每个资源创建一个新的 DTO。

作为一个简单的例子,我正在做这样的事情:

class BootDtoTransformer implements DataTransformerInterface
{

    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function transform($data, string $to, array $context = [])
    {

        $owner = $this->security->getUser();

        return $new Book($owner, $data->name);;
    }

    public function supportsTransformation($data, string $to, array $context = []): bool
    {

        if ($data instanceof Book) {
            return false;
        }

        return Book::class === $to && null !== ($context['input']['class'] ?? null);
    }

}

这在逻辑上仅适用于单个资源。为了有一个用于多种资源的通用转换器,我最终使用了一些接口(interface)来区分“可拥有”资源,并通过一些反射来实例化每个类。

我原以为这在非规范化阶段是可行的,但我无法让它发挥作用。

关于php - 使用Api-Platform,如何在创建时自动将授权用户添加为资源所有者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48052404/

相关文章:

php - Symfony 4 - 使用服务加密/解密理论中使用的字段?

symfony - Easy Admin - 在 Show Action 中显示完整的国家名称

PHP编码约定?

javascript - 将 JSON 值发送到 PHP

php - 快速数据库作为 PHP 数组的替代品

php - 使用 Symfony2 和 Doctrine 导入数据库

php - Symfony2 Sonata 项目 sonata_type_model 与 OneToMany 实体 sortby

php - Symfony 4 SwiftMailer Gmail : Email not sent

symfony - 如何更改某些 Controller 的 Monolog channel Symfony 3.4 或 4+

php - 如何在 yii 2 中通过搜索和过滤获取外键值而不是 GridView 中的键?