繁体   English   中英

Symfony4 API控制器父级

[英]Symfony4 API Controller Parent

我在Symfony4下实现了一个用于创建API的应用程序。 我希望为CRUD创建一个父控制器,该父控制器将在其他控制器上进行扩展,以避免复制所有CRUD代码。 你有例子吗? 这是我已经在控制器上执行的操作。

<?php

namespace App\Controller;

use App\Entity\Article;
use App\Exception\ResourceValidationException;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Nelmio\ApiDocBundle\Annotation\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use App\Representation\Articles;
use Symfony\Component\Validator\ConstraintViolationList;
use Swagger\Annotations as SWG;

class ArticleController extends FOSRestController
{
    /**
     * @Rest\Get(
     *     path="/api/articles/{id}",
     *     name="app_article_show",
     *     requirements={"id"="\d+"}
     * )
     * @Rest\View()
     *
     * @SWG\Response(
     *     response=200,
     *     description="Return article."
     * )
     * @SWG\Tag(name="Article")
     * @Security(name="Bearer")
     */
    public function showAction(Article $article)
    {
        return $article;
    }

    /**
     * @Rest\Post(
     *     path = "/api/articles",
     *     name= "app_article_create",
     *  )
     * @Rest\View(StatusCode= 201)
     * @ParamConverter(
     *     "article", converter="fos_rest.request_body",
     *     options={
                "validator"={ "groups"="Create"}
     *     }
     * )
     * @SWG\Response(
     *     response=200,
     *     description="Create article"
     * )
     * @SWG\Tag(name="Article")
     * @Security(name="Bearer")
     */
    public function createAction(Article $article, ConstraintViolationList $violations)
    {
        if (count($violations)) {
            $message = 'The JSON sent contain invalid data: ';
            foreach ($violations as $violation) {
                $message .= sprintf(
                    "Field %s: %s",
                    $violation->getPropertyPath(),
                    $violation->getMessage()
                );
            }
            throw new ResourceValidationException($message);
        }

        $em = $this->getDoctrine()->getManager();

        $em->persist($article);
        $em->flush();

        return $this->view(
            $article,
            Response::HTTP_CREATED,
            [
                'Location' => $this->generateUrl('app_article_create', ['id', $article->getId()], UrlGeneratorInterface::ABSOLUTE_URL)
            ]
        );
    }

    /**
     * @Rest\Get(
     *     path="/api/articles",
     *     name="app_article_list"
     * )
     * @Rest\QueryParam(
     *     name="keyword",
     *     requirements="[a-zA-Z0-9]",
     *     nullable=true,
     *     description="The keyword to search for."
     * )
     * @Rest\QueryParam(
     *     name="order",
     *     requirements="asc|desc",
     *     default="asc",
     *     description="Sort order (asc or desc)"
     * )
     * @Rest\QueryParam(
     *     name="limit",
     *     requirements="\d+",
     *     default="16",
     *     description="Max number of movies per page."
     * )
     * @Rest\QueryParam(
     *     name="offset",
     *     requirements="\d+",
     *     default="1",
     *     description="The pagination offset"
     * )
     * @Rest\View()
     * @SWG\Response(
     *     response=200,
     *     description="List all articles."
     * )
     * @SWG\Tag(name="Article")
     * @Security(name="Bearer")
     */
    public function listAction(ParamFetcherInterface $paramFetcher)
    {
        $pager = $this->getDoctrine()->getRepository(Article::class)->search(
            $paramFetcher->get('keyword'),
            $paramFetcher->get('order'),
            $paramFetcher->get('limit'),
            $paramFetcher->get('offset')
        );

        return new Articles($pager);
    }
}

谢谢您的帮助。

在Symfony 4之前,您可以使用Doctrine CRUD控制器生成功能 如果您只想举个例子,请看看。

现在,您可以使用Symfony Maker Bundle作为新的替代品。 他们在这里说,有一个新的命令make:crud ,他们改进了现有的make:form

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM