Symfony 3.x 4.x pagination

App\Entity\Product.php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 * @ORM\Table(name="product")
*/
class Product
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank(message="No puede estar vacio")
     */
    private $name;

    /**
     * @ORM\column(type="decimal", scale=2)
     */
    private $price;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank(message="No puede estar vacio")
     */
    private $description;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getPrice()
    {
        return $this->price;
    }

    public function setPrice($price)
    {
        $this->price = $price;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }
}
App\Repository\ProductRepository.php

namespace App\Repository;

use Doctrine\ORM\EntityRepository;
use App\Repository\Mapper\SearchParameter;
use App\Repository\Mapper\SearchResult;

class ProductRepository extends EntityRepository
{
    public function search(SearchParameter $sp) : SearchResult
    {
        $qb = $this->getEntityManager()->createQueryBuilder();

        $qb->select('p')
           ->from('App:Product', 'p')
           ->setFirstResult($sp->offset)
           ->setMaxResults($sp->limit)
        ;

        if (!is_null($sp->order) && !is_null($sp->orientation)) {
            $qb->orderBy($sp->order, $sp->orientation);
        }

        if (isset($sp->fields['name'])) {
            $qb->andWhere('p.name like :name')
               ->setParameter('name', "%{$sp->fields['name']}%")
            ;
        }

        if (isset($sp->fields['price'])) {
            $qb->andWhere('p.price = :price')
               ->setParameter('price', (float) $sp->fields['price'])
            ;
        }

        $result = $qb->getQuery()->getResult();

        $count = $qb->select('count(p.id)')
            ->resetDQLPart('orderBy')
            ->setFirstResult(null)
            ->setMaxResults(null)
            ->getQuery()
            ->getSingleScalarResult()
        ;

        return SearchResult::create([
            'result' => $result,
            'count' => $count,
            'page' => $sp->page,
            'limit' => $sp->limit
        ]);
    }
}
App\Repository\Mapper\SearchParameter.php

namespace App\Repository\Mapper;

class SearchParameter
{
    const LIMIT = 15;

    public $page;

    public $limit;

    public $offset;

    public $order;

    public $orientation;

    public $fields;

    public function __construct(
        int $page,
        int $limit,
        int $offset,
        string $order = null,
        string $orientation = null,
        array $fields = []
    ) {
        $this->page = $page;
        $this->limit = $limit;
        $this->offset = $offset;
        $this->order = $order;
        $this->orientation = $orientation;
        $this->fields = $fields;
    }

    public static function create(array $params)
    {
        $page = isset($params['page']) && preg_match("/^((?!(1)$)[0-9]+)$/", $params['page'])
            ? (int) $params['page']
            : 0
        ;

        $limit = isset($params['limit']) && preg_match("/^[0-9]+$/", $params['limit'])
            ? (int) $params['limit']
            : self::LIMIT
        ;

        $offset = $page > 1
            ? (($page - 1) * $limit)
            : 0
        ;

        $order = isset($params['order']) && strlen(trim($params['order'])) > 0
            ? $params['order']
            : null
        ;

        $orientation = (
                !is_null($order) && isset($params['orientation'])
                && preg_match("/^(asc|desc)$/", $params['orientation'])
            )
            ? $params['orientation']
            : null
        ;

        $fields = $params;

        return new self($page, $limit, $offset, $order, $orientation, $fields);
    }

}
App\Repository\Mapper\SearchResult.php;

class SearchResult
{
    public $count = 0;
    public $countDisplayed = 0;
    public $limit = 0;
    public $page = 1;
    public $pageFirst = 1;
    public $pageLast = 0;
    public $pagePrev = 0;
    public $pageNext = 0;
    public $pageCount = 0;
    public $result = [];

    public static function create(array $data)
    {
        $result = $data['result'] ?? [];
        $count = $data['count'] ?? 0;
        $countDisplayed = count($result);
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 0;

        return new self($result, $count, $countDisplayed, $page, $limit);
    }

    public function __construct(
        array $result,
        int $count,
        int $countDisplayed,
        int $page,
        int $limit
    ) {
        $this->result = $result;

        # total records
        $this->count = $count;

        # limit records
        $this->limit = $limit;

        # page current
        $this->page = ($page <= 0 ? 1 : $page);

        # total records displayed
        $this->countDisplayed = $countDisplayed;

        # total pages
        $this->pageCount = ($limit > 0 ? ceil($count / $limit) : 0);

        $this->pagePrev = ($this->page > 1 ? $this->page - 1 : 0);

        $this->pageNext =  $this->page < $this->pageCount ? $this->page + 1 : 0;

        $this->pageLast = $this->pageCount;
    }
}
App\Service\ProductService.php

namespace App\Service;

class ProductService extends AbstractEntityService
{
    const ENTITY = \App\Entity\Product::class;
}
App\Service\AbstractEntityService.php

namespace App\Service;

use \App\Repository\Mapper\SearchParameter;
use \App\Repository\Mapper\SearchResult;

abstract class AbstractEntityService implements EntityServiceInterface
{
    protected $conn;

    protected $em;

    protected $validator;

    protected $logger;

    public function __construct(
        \Doctrine\DBAL\Driver\Connection $conn,
        \Doctrine\ORM\EntityManagerInterface $em,
        \Symfony\Component\Validator\Validator\ValidatorInterface $validator,
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->conn = $conn;
        $this->em = $em;
        $this->validator = $validator;
        $this->logger = $logger;
    }

    /**
     * Customize search method in the entity repository class
     */
    public function search(array $params = []): SearchResult
    {
        return $this->em->getRepository(static::ENTITY)->search(
            SearchParameter::create($params)
        );

    }

    public function getById($id)
    {
        return $this->em->getRepository(static::ENTITY)->find($id);
    }

    public function save(\App\Entity\EntityInterface $entity) : bool
    {
        $errors = $this->validator->validate($entity);

        if (count($errors) > 0) {
            throw new \Exception((string) $errors);
        }

        $this->em->persist($entity);

        $this->em->flush();

        return true;
    }

    public function delete(\App\Entity\EntityInterface $entity) : bool
    {
        $this->em->remove($entity);

        $this->em->flush();

        return true;
    }
}
App\Service\EntityServiceInterface.php;


namespace App\Service;

use \App\Repository\Mapper\SearchResult;

interface EntityServiceInterface
{
    public function __construct(
        \Doctrine\DBAL\Driver\Connection $conn,
        \Doctrine\ORM\EntityManagerInterface $em,
        \Symfony\Component\Validator\Validator\ValidatorInterface $validator,
        \Psr\Log\LoggerInterface $logger
    );

    public function search(array $params = []) : SearchResult;

    public function getById($id);

    public function save(\App\Entity\EntityInterface $entity);

    public function delete(\App\Entity\EntityInterface $entity);
}
App\Controller\ProductController.php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class ProductController extends AbstractController
{
   private $entityService;

    public function __construct(\App\Service\ProductService $entityService)
    {
       $this->entityService = $entityService;
    }

    public function search(Request $request)
    {
        $form = $this->createForm(
            '\App\Form\ProductSearchType', null, [
                'method' => 'GET',
                'csrf_protection' => false
            ]
        );

        $form->handleRequest($request);

        $params = $form->isSubmitted() && $form->isValid()
            ? $form->getData()
            : []
        ;

        return $this->render(
            'Product/search.html.twig', [
                'form' => $form->createView(),
                'search' => $this->entityService->search($params)
            ]
        );
    }
}
App\Form\ProductSearchType.php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

class ProductSearchType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', null, [
                'required' => false
            ])
            ->add('price', MoneyType::class, [
                'currency' => null,
                'required' => false
            ])
            ->add('order', ChoiceType::class, [
                'label' => 'Orden',
                'required' => true,
                'choices' => [
                    'Id' => 'p.id',
                    'Nombre' => 'p.name',
                    'Precio' => 'p.price'
                ]
            ])
            ->add('orientation', ChoiceType::class, [
                'label' => 'Orientación',
                'required' => true,
                'choices' => [
                    'Ascendente' => 'asc',
                    'Descendente' => 'desc'
                ]
            ])
            ->add('page', HiddenType::class, [
                'required' => false,
                'empty_data' => true
            ]);
    }
}
templates\Product\search.html.twig


{{ form_start(form, {'method': 'GET'}) }}
Filtros
{{ form_widget(form) }}
{{ form_end(form) }}
{% if search.count == 0 %} {% else %}
Resultados {{ search.count }}, página {{ search.page }}/{{ search.pageCount }}
{% for product in search.result %} {% endfor %}
ID Name Price
{{ product.getId() }} {{ product.getName() }} {{ product.getPrice() }}
{% set queryString = app.request.query.all %} {% if search.pageCount > 1 %} {% endif %} {% endif %}

Comentarios

Entradas populares de este blog

Docker php 7.3.x ms sql server