PHP code example of kraz / read-model

1. Go to this page and download the library: Download kraz/read-model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kraz / read-model example snippets


use Kraz\ReadModel\ReadDataProviderInterface;
use Kraz\ReadModelDoctrine\DataSource;
use Kraz\ReadModelDoctrine\DataSourceBuilder;
use Kraz\ReadModelDoctrine\RawQueryReadDataProvider;

class ProductsReadModel implements ReadDataProviderInterface
{
    use RawQueryReadDataProvider;

    public function __construct(private readonly Connection $connection) {}

    protected function createDataSource(): DataSource
    {
        return new DataSourceBuilder()
            ->withData(<<<'SQL'
                SELECT r.* FROM (
                    SELECT p.id, p.name, p.price, c.name AS category
                    FROM product p
                    JOIN category c ON c.id = p.category_id
                    WHERE p.deleted_at IS NULL
                ) r
                /*#WHERE#*/
                /*#ORDERBY_B#*/ORDER BY r.id ASC/*#ORDERBY_E#*/
            SQL)
            ->create($this->connection);
    }    
}

use Kraz\ReadModelDoctrine\DoctrineReadDataProvider;

class ProductsReadModel implements ReadDataProviderInterface
{
    use DoctrineReadDataProvider;

    public function __construct(private EntityManagerInterface $em) {}

    protected function createDataSource(): DataSource
    {
        $qb = $this->em->createQueryBuilder()
            ->select('r.id, r.name, r.price')
            ->from(Product::class, 'r');

        return new DataSource($qb);
    }
}

// Filters and sorting
$products = $readModel
    ->withQueryExpression(
        $readModel->qry()
            ->andWhere($readModel->expr()->greaterThan('price', 10))
            ->andWhere($readModel->expr()->equalTo('category', 'tools'))
            ->sortBy('name', SortExpression::DIR_ASC)
    )
    ->withPagination(page: 1, itemsPerPage: 20)
    ->getResult();

// $result->data   — items on this page
// $result->page   — current page
// $result->total  — total matching rows