ssv445/aggregation-builder-pagination-bundle

使用 KnpPaginatorBundle 分页 Doctrine MongoDB ODM AggregationBuilder

2.0.1 2024-01-18 09:00 UTC

This package is auto-updated.

Last update: 2024-09-18 10:40:56 UTC


README

pipeline_status

这是 Symfony 的 KnpPaginatorBundle 扩展包,允许分页 DoctrineMongoDBBundleDoctrine\ODM\MongoDB\Aggregation\Builder

需求

Bundle 使用 MongoDB $facet 操作符,该操作符从 MongoDB 3.4 版本开始可用。

使用 Symfony Flex 安装

打开命令行,进入您的项目目录,并执行以下命令

$ composer require ssv445/aggregation-builder-pagination-bundle

使用 Symfony Flex 之外的方式安装

步骤 1:下载 Bundle

打开命令行,进入您的项目目录,并执行以下命令以下载此 Bundle 的最新稳定版本

$ composer require ssv445/aggregation-builder-pagination-bundle

步骤 2:启用 Bundle

然后,通过将其添加到项目中 config/bundles.php 文件中注册的 Bundle 列表中来启用此 Bundle

// config/bundles.php

return [
    // ...
    Ludo\Bundle\AggregationBuilderPaginationBundle\LudoAggregationBuilderPaginationBundle::class => ['all' => true],
];

使用方法

Doctrine\ODM\MongoDB\Aggregation\Builder 需要传递给 paginate() 方法。请注意,大多数 Builder 方法都返回 Doctrine\ODM\MongoDB\Aggregation\Stage。因此,您需要执行例如。

// src/Repository/ExampleRepository.php
use Doctrine\ODM\MongoDB\Aggregation\Builder as AggregationBuilder;
// ...

class ExampleRepository extends Repository
{
    public function getExamples(): AggregationBuilder
    {
        $ab = $this->createAggregationBuilder();
        
        $ab->hydrate(Example::class)
            ->match()
                ->field('field')
                ->equals('value');
        
        return $ab;
    }
}

由于 ->equals('value') 不会返回 AggregationBuilder,如果直接返回该方法的输出,代码将抛出 Exception。现在要分页示例存储库方法,您可以直接这样做

// src/Subfolder/ExamplePagination.php
// ...

class ExamplePagination
{
    // ...

    public function __construct(DocumentManager $manager, PaginatorInterface $paginator)
    {
        $this->manager = $manager;
        $this->paginator = $paginator;
    }

    public function getPaginatedExamples(): PaginationInterface
    {
        return $this->paginator->paginate(
            $this->manager->getRepository(ExampleRepository::class)->getExamples()
        );
    }
}