PHP code example of grifart / tables

1. Go to this page and download the library: Download grifart/tables 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/ */

    

grifart / tables example snippets


    

    use Grifart\Tables\Scaffolding\TablesDefinitions;

    // create a DI container, the same way as you do in your application's bootstrap.php, e.g.
    $container = App\Bootstrap::boot();

    // grab the definitions factory from the container
    $tablesDefinitions = $container->getByType(TablesDefinitions::class);

    return $tablesDefinitions->for(
        'public', // table schema
        'article', // table name
        ArticleRow::class,
        ArticleChangeSet::class,
        ArticlesTable::class,
        ArticlePrimaryKey::class,
    );
    

$rows = $table->getAll($orderBy, $paginator);

$row = $table->find(ArticlePrimaryKey::of($articleId));
// or
$row = $table->get(ArticlePrimaryKey::of($articleId));

$rows = $table->findBy($conditions, $orderBy, $paginator);

$row = $table->getUniqueBy($conditions);
$rowOrNull = $table->findUniqueBy($conditions);

$row = $table->getFirstBy($conditions, $orderBy);
$rowOrNull = $table->findFirstBy($conditions, $orderBy);

$rows = $table->findBy(
    Composite::and(
        $table->published()->is(equalTo(true)),
        $table->createdAt()->is(lesserThanOrEqualTo(Instant::now())),
    ),
);

$rows = $table->findBy([
    $table->published()->is(equalTo(true)),
    $table->createdAt()->is(lesserThanOrEqualTo(Instant::now())),
]);

$rows = $table->findBy([
    $table->published()->is(true),
    $table->createdAt()->is(lesserThanOrEqualTo(Instant::now())),
]);

use Grifart\Tables\Expression;
use Grifart\Tables\Types\TextType;

final class IsLike implements Condition
{
	/**
	 * @param Expression<string> $expression
	 */
	public function __construct(
		private Expression $expression,
		private string $pattern,
	) {}

	public function toSql(): \Dibi\Expression
	{
		return new \Dibi\Expression(
			'? LIKE ?',
			$this->expression->toSql(),
			TextType::varchar()->toDatabase($this->pattern),
		);
	}
}

$rows = $table->findBy([
    new IsLike($table->title(), 'Top 10%'),
]);

function like(string $pattern) {
    return static fn(Expression $expression) => new IsLike($expression, $pattern);
}

$rows = $table->findBy([
    $table->title()->is(like('Top 10%')),
]);

use Grifart\Tables\Expression;
use Grifart\Tables\Types\IntType;
use Grifart\Tables\Type;

/**
 * @implements Expression<int>
 */
final class Year implements Expression
{
    /**
     * @param Expression<\Brick\DateTime\Instant>|Expression<\Brick\DateTime\LocalDate> $sub
    */
    public function __construct(
        private Expression $sub,
    ) {}

    public function toSql(): \Dibi\Expression
    {
        return new \Dibi\Expression(
            "EXTRACT ('year' FROM ?)",
            $this->sub->toSql(),
        );
    }

    public function getType(): Type
    {
        return IntType::integer();
    }
}

/**
 * @extends ExpressionWithShorthands<int>
 */
final class Year extends ExpressionWithShorthands
{
    // ...
}

$rows = $table->findBy(
    (new Year($table->createdAt()))->is(equalTo(2021)),
);

$year = fn(Expression $expr) => expr(IntType::integer(), "EXTRACT ('year' FROM ?)", $expr->toSql());
$rows = $table->findBy(
    $year($table->createdAt())->is(equalTo(2021)),
);

$rows = $table->getAll(orderBy: [
    $table->createdAt()->descending(),
    $table->title(), // ->ascending() is the default
]);

$paginator = new \Nette\Utils\Paginator();
$paginator->setItemsPerPage(20);
$paginator->setPage(2);

$rows = $table->getAll($orderBy, $paginator);

$changeSet = $table->new(
    id: \Ramsey\Uuid\Uuid::uuid4(),
    title: 'Title of the post',
    text: 'Postt text',
    createdAt: \Brick\DateTime\Instant::now(),
    published: true,
);

$changeSet->modifyText('Post text');
$table->insert($changeSet);

$changeSet = $table->edit(ArticlePrimaryKey::from($articleId));
// or
$changeSet = $table->edit($articleRow);

$changeSet = $table->edit(
    $articleRow,
    deletedAt: \Brick\DateTime\Instant::now(),
);

$changeSet->modifyDeletedAt(\Brick\DateTime\Instant::now());
$table->update($changeSet);

$table->delete(ArticlePrimaryKey::from($articleId));
// or
$table->delete($articleRow);

/**
 * @implements Type<Currency>
 */
final class CurrencyType implements Type
{
	public function getPhpType(): PhpType
	{
		return resolve(Currency::class);
	}

	public function getDatabaseType(): DatabaseType
	{
		return BuiltInType::char();
	}

	public function toDatabase(mixed $value): Expression
	{
		return $value->getCode();
	}

	public function fromDatabase(mixed $value): mixed
	{
		return Currency::of($value);
	}
}

$dateArrayType = ArrayType::of(new DateType());

$nullableDateArrayType = ArrayType::of(NullableType::of(new DateType()));

enum Status: string {
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
}

$statusType = EnumType::of(Status::class);

$moneyType = new class extends CompositeType {
    public function __construct()
    {
        parent::__construct(
            new Database\NamedType(new Database\Identifier('public', 'money')),
            DecimalType::decimal(),
            new CurrencyType(), // custom type from above
        );
    }

    public function getPhpType(): PhpType
    {
        return resolve(Money::class);
    }

    public function toDatabase(mixed $value): Dibi\Expression
    {
        return $this->tupleToDatabase([
            $value->getAmount(),
            $value->getCurrency(),
        ]);
    }

    public function fromDatabase(mixed $value): Money
    {
        [$amount, $currency] = $this->tupleFromDatabase($value);
        return Money::of($amount, $currency);
    }
};

$nullableDateArrayType = ArrayType::of(NullableType::of(new DateType()));

$moneyType = new class extends CompositeType {
    public function __construct()
    {
        parent::__construct(
            new Database\NamedType(new Database\Identifier('public', 'money')),
            NullableType::of(DecimalType::decimal()),
            new CurrencyType(),
        );
    }

    // ...
}