
本文介绍了如何在使用 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 Symfony\Component\Serializer\Annotation\Groups;
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 Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\Invoice;
use App\Service\InvoiceDocumentService;
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 Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route('/invoices/{id}/document', name: 'invoice_document', methods: ['GET'])]
#[IsGranted('ROLE_ADMIN')] // 示例:只有管理员可以访问
public function getDocument(Invoice $invoice): Response
{
// ...
}或者,更细粒度的权限控制,可以实现 Voter:
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use App\Entity\Invoice;
use App\Entity\User;
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 以支持不同的输出格式的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号