1. Go to this page and download the library: Download devitools/constructo 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/ */
devitools / constructo example snippets
# ...
use Constructo\Core\Serialize\Builder;
use Constructo\Support\Set;
use Constructo\Type\Timestamp;
// Defina sua entidade informando os valores das propriedades no construtor
readonly class User
{
public function __construct(
public int $id,
public string $name,
public Timestamp $birthDate,
public bool $isActive = true,
public array $tags = [],
) {}
}
// Monte um set com os dados (de JSON, banco de dados, etc.)
$set = Set::createFrom([
'id' => 1,
'name' => 'João Silva',
'birth_date' => '1981-08-13',
'is_active' => true,
'tags' => ['nice', 'welcome'],
]);
// Crie um novo builder e use-o para construir o objeto
$user = (new Builder())->build(User::class, $set);
echo "Usuário: \n";
echo sprintf(" ID: %s\n", $user->id);
echo sprintf(" Nome: %s\n", $user->name);
echo sprintf(" Ativo: %s\n", $user->isActive);
echo sprintf(" Tags: %s\n", implode(', ', $user->tags));
echo sprintf(" Data de Nascimento: %s\n", $user->birthDate->format('Y-m-d'));
use Constructo\Core\Deserialize\Demolisher;
// Crie uma instância
$user = new User(1, 'João Silva', '[email protected]', true, ['admin', 'usuario']);
// Serialize para objeto/array
$demolisher = new Demolisher();
$data = $demolisher->demolish($user);
echo json_encode($data);
// Saída: {"id":1,"name":"João Silva","email":"[email protected]","isActive":true,"tags":["admin","usuario"]}
use Constructo\Core\Serialize\Builder;
// Formatador personalizado para arrays
class ArrayFormatter
{
public function __invoke($value)
{
return is_string($value) ? json_decode($value, true) : $value;
}
}
// Use com Builder
$builder = new Builder(formatters: [
'array' => new ArrayFormatter(),
]);
$data = [
'id' => 1,
'name' => 'Maria Santos',
'tags' => '["desenvolvedor", "php"]' // String JSON será convertida para array
];
$user = $builder->build(User::class, Set::createFrom($data));
echo implode(', ', $user->tags); // "desenvolvedor, php"
class Address extends Entity
{
public function __construct(
public readonly string $street,
public readonly string $city,
public readonly string $country
) {}
}
class User extends Entity
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly Address $address,
public readonly ?DateTime $createdAt = null
) {}
}
// Dados aninhados
$data = [
'id' => 1,
'name' => 'João Silva',
'address' => [
'street' => 'Rua Principal, 123',
'city' => 'São Paulo',
'country' => 'Brasil'
],
'created_at' => '2023-01-15T10:30:00+00:00'
];
$builder = new Builder();
$user = $builder->build(User::class, Set::createFrom($data));
echo $user->address->city; // "São Paulo"
echo $user->createdAt->format('d/m/Y'); // "15/01/2023"
enum Status: string
{
case ACTIVE = 'ativo';
case INACTIVE = 'inativo';
case PENDING = 'pendente';
}
class Order extends Entity
{
public function __construct(
public readonly int $id,
public readonly Status $status,
public readonly float $amount
) {}
}
$data = [
'id' => 1,
'status' => 'ativo', // String será convertida para enum
'amount' => 99.99
];
$builder = new Builder();
$order = $builder->build(Order::class, Set::createFrom($data));
echo $order->status->value; // "ativo"
use Constructo\Support\Datum;
use Constructo\Exception\AdapterException;
try {
$result = $builder->build(User::class, Set::createFrom($invalidData));
} catch (AdapterException $e) {
// Crie um objeto Datum com detalhes do erro
$datum = new Datum($e, $invalidData);
$errorData = $datum->export();
// Contém dados originais mais '@error' com detalhes da exceção
}
use Constructo\Core\Deserialize\Demolisher;
// Formatador de string personalizado
$stringFormatter = fn($value) => sprintf('[%s]', $value);
// Use com Demolisher
$demolisher = new Demolisher(formatters: [
'string' => $stringFormatter,
]);
$user = new User(1, 'Ana Costa', '[email protected]');
$data = $demolisher->demolish($user);
echo $data->name; // "[Ana Costa]"
use Constructo\Contract\Collectable;
use Constructo\Type\Collection;
class UserCollection extends Collection implements Collectable
{
protected function getItemClass(): string
{
return User::class;
}
}
// Serialize coleção
$collection = new UserCollection();
$collection->push($user1);
$collection->push($user2);
$demolisher = new Demolisher();
$arrayData = $demolisher->demolishCollection($collection);
use function Constructo\Json\decode;
use function Constructo\Json\encode;
$array = decode('{"name":"João","age":30}');
$json = encode(['name' => 'João', 'age' => 30]);
use function Constructo\Cast\arrayify;
use function Constructo\Cast\stringify;
$array = arrayify($data); // Converte para array com segurança
$string = stringify($value); // Converte para string com segurança
use function Constructo\Util\extractString;
use function Constructo\Util\extractInt;
use function Constructo\Util\extractBool;
use function Constructo\Util\extractArray;
$name = extractString($data, 'name', 'padrão');
$age = extractInt($data, 'age', 0);
$active = extractBool($data, 'is_active', false);
$tags = extractArray($data, 'tags', []);
use Constructo\Testing\BuilderExtension;
use Constructo\Testing\MakeExtension;
use PHPUnit\Framework\TestCase;
class MyTest extends TestCase
{
use BuilderExtension, MakeExtension;
public function testSerialization(): void
{
$user = $this->builder()->build(User::class, Set::createFrom($data));
$this->assertInstanceOf(User::class, $user);
}
}
use Constructo\Support\Entity;
class MyEntity extends Entity
{
// Automaticamente implementa Exportable e JsonSerializable
// Fornece método export() que retorna objeto com todas as propriedades públicas
}
use Constructo\Support\Set;
$set = Set::createFrom(['key' => 'valor']);
$set = new Set(['key' => 'valor']);
$value = $set->get('key', 'padrão');
$array = $set->toArray();
use Constructo\Support\Value;
$value = new Value('alguns dados');
// Fornece vários métodos para manipulação e validação de valores
use Constructo\Factory\SchemaFactory;
use Constructo\Factory\DefaultSpecsFactory;
$schemaFactory = new SchemaFactory(new DefaultSpecsFactory());
$schema = $schemaFactory->make();
use Constructo\Support\Reflective\Engine;
use Constructo\Factory\ReflectorFactory;
$reflectorFactory = new ReflectorFactory();
$reflector = $reflectorFactory->make();
use Constructo\Support\Cache;
$cache = new Cache();
// Fornece mecanismos de cache para dados de reflexão e schemas
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.