PHP code example of jasny / entity

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

    

jasny / entity example snippets


namespace App;

use Jasny\Entity\IdentifiableEntityInterface;
use Jasny\Entity\IdentifiableEntityTraits;

/**
 * A user in our system
 */
class User extends AbstractIdentifiableEntity
{
    /** @var string */
    public $id;
    
    /** @var string */
    public $name;
    
    /** @var string */
    public $email;
    
    /** @var string */
    public $password_hash;
}

use App\User;
use Jasny\Entity\Event;

$data = $db->prepare("SELECT * FROM user WHERE id = ?")->execute($id)->fetch(PDO::FETCH_ASSOC);
$user = User::fromData($data);

$user->addEventListener(function(Event\ToJson $event): void {
    $data = $event->getPayload();
    unset($data['password_hash']);

    $event->setPaypload($data);
});

header('Content-Type: application\json');
echo json_serialize($user);

class Color extends AbstractBasicEntity
{
    /** @var int */
    public $red;
    
    /** @var int */
    public $green;
    
    /** @var int */
    public $blue;
}

class User extends AbstractIdentifiableEntity
{
    /** @var int */
    public $id;
    
    /** @var string */
    public $name;
    
    /** @var string */
    public $email;
    
    /** @var string */
    public $password_hash;
}

class Invoice extends AbstractIdentifiableEntity
{
    /** @var string */
    public $number;
    
    // ...
    
    protected static function getIdProperty(): string
    {
        return 'number';
    }
}

class User extends AbstractIdentifiableEntity implements DynamicEntity
{
    // ...
}

$user = new User(); // This represents a new user in the system

$data = $db->prepare("SELECT * FROM user WHERE id = ?")->execute($id)->fetch(PDO::FETCH_ASSOC);
$user = User::fromData($data);

$foo = new Foo();
$foo->set('answer', 42);
$foo->set(['red' => 10, 'green' => 20, 'blue' => 30]);

$adventure = (new Adventure)
  ->set('destination', 'unknown')
  ->set('duration', '1 year')
  ->go();

$data = $user->toAssoc();

$user->addEventListener(function(Event\ToAssoc $event): void {
    $assoc = $event->getPayload();
    
    if (isset($assoc['password'])) {
        $assoc['password_hashed'] = password_hash($assoc['password'], PASSWORD_DEFAULT);
        unset($assoc['password_hashed']);
    }
    
    $event->setPayload($assoc);
});

$user->addEventListener(function(Event\ToJson $event): void {
    $assoc = $event->getPayload();
    unset($assoc['password_hashed']);
    
    $event->setPayload($assoc);
});

class UserGateway
{
    /** @var \PDO */
    protected $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function load(string $id): User
    {
        $data = $db->prepare("SELECT * FROM user WHERE id = ?")->execute($id)->fetch(PDO::FETCH_ASSOC);
        
        if ($data === null) {
            throw new RuntimeException("User `$id` not found");
        }
        
        return User::fromData($data);
    }
    
    public function save(User $user): void
    {
        $data = $user->toAssoc();
        
        $columns = join(', ', array_keys($data));             // "id, name, email, password_hash"
        $placeholders = ':' . join(', :', array_keys($data)); // ":id, :name, :email, :password_hash"
        
        $db->prepare("REPLACE INTO users ($columns) VALUES ($placeholders)")->execute();
        
        $user->markAsPersisted();
    }
}

use Jasny\Entity\Event;
use Jasny\Entity\EventListener\JsonCast;
use Jasny\EventDispatcher\EventDispatcher;

$listener = (new ListenerProvider)
    ->withListener(function(Event\Serialize $event): void {
        $assoc = $event->getPayload();
        
        if (isset($assoc['password'])) {
            $assoc['password_hashed'] = password_hash($assoc['password'], PASSWORD_DEFAULT);
            unset($assoc['password_hashed']);
        }
        
        $event->setPayload($assoc);
    })
    ->withListener(new JsonCast());
    
$dispatcher = new EventDispatcher($listener);

$user = new User;
$user->setEventDispatcher($dispatcher);

$user->addEventListener(function(Event\ToJson $event): void {
    $assoc = $event->getPayload();
    unset($assoc['password_hashed']);
    
    $event->setPayload($assoc);
});

$event = $user->dispatchEvent(new CustomEvent($user, $someData));