doujia6503 2018-06-14 12:34
浏览 41
已采纳

JMS组序列化和PagerFantaBundle

I'm working on a RESTFull API with Symfony and FOSRESTBundle. I use the JMS Serializer with groups to show differents fields depending on the context.

For listing my resources, I want implement PagerFantaBundle. All work fine except that PagerFanta does not consider the serialization groups.

Below my code :

Pagination function :

 protected function paginate(QueryBuilder $qb, $limit = 20, $offset = 0) {
    if($limit == 0 || $offset < 0) {
        throw new \LogicException("$limit & $offset must be greater than 0");
    }

    $pager = new Pagerfanta(new DoctrineORMAdapter($qb));
    $currentPage = ceil($offset + 1 / $limit);
    $pager->setCurrentPage($currentPage);
    $pager->setMaxPerPage((int) $limit);

    return $pager;
}

List apartment function :

public function listApartments(Location $location, $order = 'asc', $limit = 20, $offset = 0) {
    $qb = $this->createQueryBuilder('a')
        ->select('a')
        ->orderBy('a.title', $order);

    return $this->paginate($qb, $limit, $offset);
}

Controller :

/**
 * @Rest\Get(
 *     path = "/apartments",
 *     name = "apartments_get_all"
 * )
 * @Rest\QueryParam(
 *     name="order",
 *     requirements="asc|desc",
 *     nullable=true,
 *     description="Sort order (asc or desc)"
 * )
 * @Rest\QueryParam(
 *     name="limit",
 *     requirements="\d+",
 *     default="20",
 *     description="Max number of apartments per page"
 * )
 * @Rest\QueryParam(
 *     name="offset",
 *     requirements="\d+",
 *     default="0",
 *     description="Pagination offset"
 * )
 * @Rest\View(statusCode=200, serializerGroups={"listApartment"})
 */
public function getApartmentsAction(ParamFetcherInterface $paramFetcher)
{
    $pager = $this->getDoctrine()->getRepository("HGBCoreBundle:Apartment")->listApartments(
        new Location(),
        $paramFetcher->get('order'),
        $paramFetcher->get('limit'),
        $paramFetcher->get('offset')
    );

    return new Apartments($pager);
}

Apartments representation :

class Apartments
{
/**
 * @Type("array<HGB\CoreBundle\Entity\Apartment>")
 */
public $data;

public $meta;

public function __construct(Pagerfanta $data)
{
    $this->data = $data->getCurrentPageResults();

    $this->addMeta('limit', $data->getMaxPerPage());
    $this->addMeta('current_items', count($data->getCurrentPageResults()));
    $this->addMeta('total_items', $data->getNbResults());
    $this->addMeta('offset', $data->getCurrentPageOffsetStart());
}

public function addMeta($name, $value)
{
    if (isset($this->meta[$name])) {
        throw new \LogicException(sprintf('This meta already exists. You are trying to override this meta, use the setMeta method instead for the %s meta.', $name));
    }

    $this->setMeta($name, $value);
}

public function setMeta($name, $value)
{
    $this->meta[$name] = $value;
}
}

Apartment Entity :

/**
 * Apartment
 *
 * @ORM\Table(name="apartment")
 * @ORM\Entity(repositoryClass="HGB\CoreBundle\Repository\ApartmentRepository")
 * @JMS\ExclusionPolicy("all")
 */
class Apartment
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 * @JMS\Groups({"listApartment"})
 * @JMS\Expose()
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="title", type="string", length=200)
 * @JMS\Groups({"listApartment"})
 * @JMS\Expose()
 * @Assert\NotBlank()
 */
private $title;
...

So, how can I use group serialization with PagerFanta, or what pagination system could I use with groups serialization ?

Thanks

  • 写回答

1条回答 默认 最新

  • donglu8334 2018-06-15 09:51
    关注

    I've found the solution. Just need to configure the serialization groups for the Apartments representation like this :

    <?php
    
    
    namespace HGB\CoreBundle\Representation;
    
    
    use JMS\Serializer\Annotation as Serializer;
    use Pagerfanta\Pagerfanta;
    
    /**
     * Class Apartments
     * @package HGB\CoreBundle\Representation
     * @Serializer\ExclusionPolicy("all")
     */
    class Apartments
    {
    /**
     * @Serializer\Type("array<HGB\CoreBundle\Entity\Apartment>")
     * @Serializer\Groups("listApartment")
     * @Serializer\Expose()
     */
    public $data;
    
    /**
     * @Serializer\Groups("listApartment")
     * @Serializer\Expose()
     */
    public $meta;
    
    public function __construct(Pagerfanta $data)
    {
        $this->data = $data;
    
        $this->addMeta('limit', $data->getMaxPerPage());
        $this->addMeta('current_items', count($data->getCurrentPageResults()));
        $this->addMeta('total_items', $data->getNbResults());
        $this->addMeta('offset', $data->getCurrentPageOffsetStart());
    }
    
    public function addMeta($name, $value)
    {
        if (isset($this->meta[$name])) {
            throw new \LogicException(sprintf('This meta already exists. You are trying to override this meta, use the setMeta method instead for the %s meta.', $name));
        }
    
        $this->setMeta($name, $value);
    }
    
    public function setMeta($name, $value)
    {
        $this->meta[$name] = $value;
    }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题