DevCraft Документации

Начало работы v1.1.0

Обзор DevCraft Dev Tools, архитектура, требования и первые шаги

Пакет devcraftclub/dev-tools — библиотека PHP 8.3 с тремя взаимодополняющими возможностями:

  1. Fluent mutation и accessors#[With] / #[WithItem], #[Getter] / #[Setter] (lombok-php), AbstractWith.
  2. DTO mappingAbstractReflection, гидратация из массива, валидация атрибутами, toArray() / toJson().
  3. PSR-6 файловый кэшFileCachePool, CacheItem, clearNamespace() (с 1.1.0).

Базовые классы fluent/DTO рассчитаны на разные модели свойств и не предназначены для объединения через наследование.

Архитектура

Fluent API                              DTO Mapping                         PSR-6 Cache
───────────                             ───────────                         ───────────
#[With] / #[WithItem]                   public typed properties             FileCachePool
#[Getter] / #[Setter] (lombok-php)               │                                  │
        │                                        ▼                                  ▼
        ▼                                 AbstractReflection                 {baseDir}/{key}.cache
 AbstractWith ──__call──► WithHandler            │                          JSON envelope {e,f,v}
        │            (with* first)               ▼
        └──parent──► Lombok\Helper        ReflectionMapper
                     (get* / set* / is*)         │

                                          PropertyValidator

                            Filter / Range / Regex / ArrayOf

Разделы документации

Быстрый старт

PSR-6 кэш

use Devcraft\Cache\FileCachePool;

$pool = new FileCachePool('/path/to/cache', defaultTtlSeconds: 3600);

$item = $pool->getItem('Translation/dict');
$item->set(['hello' => 'world']);
$pool->save($item);

$hit = $pool->getItem('Translation/dict');
if ($hit->isHit()) {
    $value = $hit->get();
}

$pool->clearNamespace('Translation'); // DevTools extension (not in PSR-6)

Fluent With

use Lombok\Getter;
use Devcraft\Abstracts\AbstractWith;
use Devcraft\Attributes\With;
use Devcraft\Attributes\WithItem;

#[Getter]
final class Query extends AbstractWith
{
    #[With]
    private ?int $page = null;

    #[With, WithItem('string')]
    private array $tags = [];

    #[WithItem('string', ['string', 'null'])]
    private array $labels = [];
}

$query = (new Query())
    ->withPage(1)
    ->withTagsItem('proxy')
    ->withLabelsItem('status', 'ready');

$query->getPage();  // 1
$query->getTags();  // ['proxy']
$query->getLabels(); // ['status' => 'ready']

DTO mapping:

use Devcraft\Abstracts\AbstractReflection;
use Devcraft\Attributes\ArrayOf;
use Devcraft\Attributes\Range;
use Devcraft\Attributes\Regex;

final class Address extends AbstractReflection
{
    public string $city;
}

final class Proxy extends AbstractReflection
{
    #[Regex('/^[0-9a-f-]{36}$/i')]
    public string $id;

    #[Range(min: 1, max: 65535)]
    public int $port;

    public Address $address;

    #[ArrayOf(Address::class)]
    public array $locations = [];
}

$proxy = Proxy::fromArray([
    'id' => '550e8400-e29b-41d4-a716-446655440000',
    'port' => '8080',
    'address' => ['city' => 'Berlin'],
    'locations' => [
        ['city' => 'Berlin'],
        ['city' => 'Paris'],
    ],
]);

$proxy->port;              // int 8080 (string coerced)
$proxy->address->city;     // 'Berlin'
$proxy->toArray();         // nested arrays
echo $proxy->toJson();     // pretty-printed JSON

Выбор базового класса

НужноНаследоватьСтиль свойств
Fluent with* / query objects, плюс get* / set*AbstractWithPrivate (или protected), non-static, non-readonly
API response / request DTOAbstractReflectionPublic, typed, hydratable
Файловый PSR-6 кэш— (composition: FileCachePool)

Не комбинируйте AbstractWith и AbstractReflection через inheritance. Если нужны оба формы — composition или два отдельных класса.

Требования

Следующие шаги

На этой странице