Skip to content

Instantly share code, notes, and snippets.

@tbreuss
Last active January 30, 2021 07:54
Show Gist options
  • Save tbreuss/c01f3f6aedc187c0add06985489b2bae to your computer and use it in GitHub Desktop.
Save tbreuss/c01f3f6aedc187c0add06985489b2bae to your computer and use it in GitHub Desktop.
Simple example using PDO with FETCH_CLASS implementing a modest Entity pattern.
<?php
declare(strict_types=1);

require dirname(__DIR__) . '/../vendor/autoload.php';

class Entity
{
    public function __construct(array $data)
    {
        $this->hydrate($data);
    }

    public function __set($property, $value)
    {
        //echo $property . ' -> ' . $value . '<br>';
    }

    protected function hydrate(array $data)
    {
        foreach ($data as $key => $value) {
            $this->$key = $value;
        }
    }
}

class Birthday extends Entity
{
    protected string $id = '';
    protected string $name = '';
    protected string $birth = '';
    protected ?string $death = null;
    protected string $created = '';

    public function getId(): int
    {
        return (int)$this->id;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getBirth(): string
    {
        return $this->birth;
    }

    public function getDeath(): ?string
    {
        return $this->death;
    }

    public function getCreated(): ?string
    {
        return $this->created;
    }
}

$pdo = new PDO('mysql:host=mysql.test;dbname=birthdays', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = <<<SQL
    SELECT 
        id, 
        name, 
        birth, 
        death,
        created
    FROM birthday
    LIMIT 2
SQL;

$birthdays = $pdo->query($sql)
    ->fetchAll(PDO::FETCH_CLASS, 'Birthday', [[]]);

var_dump($birthdays);

foreach ($birthdays as $birthday) {
    echo $birthday->getId() . '<br>';
    echo $birthday->getName() . '<br>';
    echo $birthday->getBirth() . '<br>';
    echo $birthday->getDeath() . '<br>';
    echo $birthday->getDeath() . '<br>';
    echo '<br>';
}

$sql = <<<SQL
    SELECT 
        id, 
        name, 
        birth, 
        death,
        created
    FROM birthday
    WHERE id = 12
SQL;
$stm = $pdo->query($sql);
$stm->setFetchMode(PDO::FETCH_CLASS, 'Birthday', [[]]);
$birthday = $stm->fetch();


echo $birthday->getId() . '<br>';
echo $birthday->getName() . '<br>';
echo $birthday->getBirth() . '<br>';
echo $birthday->getDeath() . '<br>';
echo $birthday->getDeath() . '<br>';
echo '<br>';

$birthday = new Birthday([
    'id' => '3',
    'name' => 'Freddy Mercurie',
    'birth' => '1962-02-01',
    'death' => '2001-07-20'
]);

echo $birthday->getId() . '<br>';
echo $birthday->getName() . '<br>';
echo $birthday->getBirth() . '<br>';
echo $birthday->getDeath() . '<br>';
echo '<br>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment