通过自定义路由扩展 ApiResource 以支持不同的输出格式

通过自定义路由扩展 apiresource 以支持不同的输出格式

本文介绍了如何在使用 Api-Platform 时,为一个现有的 ApiResource (例如 Invoice) 添加一个自定义路由,该路由接受 Invoice 对象作为输入,但以 application/pdf 格式输出。我们将探讨一种通过添加一个返回 PDF URL 的方法到 Invoice 实体,并结合一个常规 Symfony 控制器来实现此目标的方法。同时,我们还会强调安全性,以防止未经授权的访问。

在使用 Api-Platform 构建 API 时,我们经常需要扩展现有 ApiResource 的功能,以满足特定的业务需求。一个常见的场景是,我们需要添加一个自定义路由,该路由使用与标准 CRUD 操作不同的输出格式。例如,我们可能希望为 Invoice 实体添加一个 /invoices/{id}/document 路由,该路由返回指定 Invoice 的 PDF 文档。

一种实现此目标的方法是利用 schema.org 的概念,将 PDF 文档视为 Invoice 的一个属性。具体来说,我们可以为 Invoice 实体添加一个 getUrl() 方法,该方法返回 PDF 文档的 URL。然后,我们可以将实际的 PDF 生成逻辑移动到一个常规的 Symfony 控制器中。

以下是具体步骤:

1. 修改 Invoice 实体

首先,我们需要向 Invoice 实体添加一个 getUrl() 方法。该方法应返回 PDF 文档的 URL。

use SymfonyComponentSerializerAnnotationGroups;class Invoice{    // ... 其他属性 ...    #[Groups(["read:invoice"])]    public function getUrl(): string    {        return "/invoices/{$this->id}/document";    }}

请注意,我们使用了 #[Groups([“read:invoice”])] 注解。这确保了 getUrl() 方法的值会在序列化 Invoice 对象时被包含在内,前提是序列化上下文包含 read:invoice 组。

2. 创建 Symfony 控制器

接下来,我们需要创建一个 Symfony 控制器来处理 /invoices/{id}/document 路由。该控制器将接收 Invoice ID 作为参数,并使用 InvoiceDocumentService 生成 PDF 文档。

use SymfonyBundleFrameworkBundleControllerAbstractController;use SymfonyComponentHttpFoundationResponse;use SymfonyComponentRoutingAnnotationRoute;use AppEntityInvoice;use AppServiceInvoiceDocumentService;class InvoiceDocumentController extends AbstractController{    private InvoiceDocumentService $documentService;    public function __construct(InvoiceDocumentService $documentService)    {        $this->documentService = $documentService;    }    #[Route('/invoices/{id}/document', name: 'invoice_document', methods: ['GET'])]    public function getDocument(Invoice $invoice): Response    {        $pdfContent = $this->documentService->createDocumentForInvoice($invoice);        $response = new Response($pdfContent);        $response->headers->set('Content-Type', 'application/pdf');        $response->headers->set('Content-Disposition', 'inline; filename="invoice_' . $invoice->getId() . '.pdf"');        return $response;    }}

在这个控制器中,我们使用了类型提示 (Invoice $invoice) 来自动获取 Invoice 实体。Api-Platform 会自动根据 URL 中的 {id} 参数查询数据库,并将对应的 Invoice 对象传递给 getDocument() 方法。

3. 安全性注意事项

重要的是要确保只有授权用户才能访问 PDF 文档。为了防止未经授权的访问,您应该添加一个安全系统来验证用户是否有权查看特定的 Invoice。例如,您可以检查用户是否与 Invoice 相关联,或者他们是否具有特定的角色。

您可以使用 Symfony 的安全组件来实现此目的。例如,您可以使用 @IsGranted 注解来限制对 getDocument() 方法的访问。

use SymfonyComponentSecurityHttpAttributeIsGranted;#[Route('/invoices/{id}/document', name: 'invoice_document', methods: ['GET'])]#[IsGranted('ROLE_ADMIN')] // 示例:只有管理员可以访问public function getDocument(Invoice $invoice): Response{    // ...}

或者,更细粒度的权限控制,可以实现 Voter:

use SymfonyComponentSecurityCoreAuthorizationVoterVoter;use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;use AppEntityInvoice;use AppEntityUser;class InvoiceVoter extends Voter{    const VIEW = 'VIEW';    protected function supports(string $attribute, mixed $subject): bool    {        // 如果 attribute 不是我们支持的,则返回 false        if (!in_array($attribute, [self::VIEW])) {            return false;        }        // 只有 Invoice 对象才能被投票        if (!$subject instanceof Invoice) {            return false;        }        return true;    }    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool    {        $user = $token->getUser();        if (!$user instanceof User) {            // 如果用户未登录,则拒绝访问            return false;        }        /** @var Invoice $invoice */        $invoice = $subject;        switch ($attribute) {            case self::VIEW:                return $this->canView($invoice, $user);        }        throw new LogicException('This code should not be reached!');    }    private function canView(Invoice $invoice, User $user): bool    {        // 逻辑判断用户是否有权查看 Invoice        // 例如,检查用户是否是 Invoice 的创建者        return $invoice->getOwner() === $user;    }}

然后在控制器中使用:

#[Route('/invoices/{id}/document', name: 'invoice_document', methods: ['GET'])]public function getDocument(Invoice $invoice, AuthorizationCheckerInterface $authChecker): Response{    if (!$authChecker->isGranted(InvoiceVoter::VIEW, $invoice)) {        throw $this->createAccessDeniedException('您无权查看此发票。');    }    // ...}

4. 总结

通过将 PDF 文档的 URL 作为 Invoice 实体的一个属性公开,并使用常规的 Symfony 控制器来处理实际的 PDF 生成逻辑,我们可以轻松地为 ApiResource 添加自定义路由,并支持不同的输出格式。重要的是要记住添加安全措施,以防止未经授权的访问。这种方法避免了创建自定义编码器和 OpenAPI 装饰器的复杂性,并提供了一种更简洁、更易于维护的解决方案。

以上就是通过自定义路由扩展 ApiResource 以支持不同的输出格式的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1270547.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月10日 13:02:43
下一篇 2025年12月10日 13:02:54

相关推荐

发表回复

登录后才能评论
关注微信