PHP code example of sugatasei / bredala-data

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

    

sugatasei / bredala-data example snippets


use Bredala\Data\ModelAbstract;

class User extends ModelAbstract
{
    public ?int $id = null;
    public string $email = '';
    public string $name = '';
}

class Post extends ModelAbstract
{
    public string $slug = '';
    public string $createdAt = '';

    public function init(): static
    {
        $this->createdAt = date('Y-m-d H:i:s');
        return $this;
    }
}

$editable = ['email', 'name'];  // ni id, ni role
$user->import(array_intersect_key($input, array_flip($editable)));

$user = User::create(['email' => '[email protected]', 'name' => 'Tom']);

$user->export();        // ['id' => null, 'email' => '[email protected]', 'name' => 'Tom']
json_encode($user);     // {"id":null,"email":"[email protected]","name":"Tom"}

use Bredala\Data\AdapterAbstract;

class UserAdapter extends AdapterAbstract
{
    public function encode(mixed $input): mixed
    {
        return ['id' => $input->id, 'email' => $input->email, 'full_name' => $input->name];
    }

    public function decode(mixed $input): mixed
    {
        return User::create([
            'id' => $input['id'] ?? null,
            'email' => $input['email'] ?? '',
            'name' => $input['full_name'] ?? '',
        ]);
    }
}

$authorIds = UserAdapter::unique($postRows, 'author_id');

use Bredala\Data\AdapterAbstract;
use Bredala\Data\ModelAbstract;

class User extends ModelAbstract
{
    public ?int $id = null;
    public string $email = '';
    public string $name = '';

    public function init(): static
    {
        $this->name = 'anonyme';
        return $this;
    }
}

class UserAdapter extends AdapterAbstract
{
    public function decode(mixed $input): mixed
    {
        return User::create([
            'id' => (int) $input['id'],
            'email' => $input['email'],
            'name' => $input['full_name'],
        ]);
    }
}

$adapter = new UserAdapter();

$rows = [
    ['id' => '1', 'email' => '[email protected]', 'full_name' => 'Tom'],
    ['id' => '2', 'email' => '[email protected]', 'full_name' => 'Tim'],
];

$users = array_map(fn(array $row) => $adapter->decode($row), $rows);

foreach ($users as $user) {
    print_r($user->export());
}