1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| <?php
namespace App\Model;
use PDO;
use App\Model\Billets;
class BilletsManager
{
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function __add(Billets $billets)
{
$q = $this->db->prepare('INSERT INTO billets(titre, contenu, dateAjout, dateModif) VALUES (:titre, :contenu, NOW(), NOW())');
$q->bindValue(':titre', $billets->titre());
$q->bindValue(':contenu', $billets->contenu());
$q->execute();
}
public function count()
{
return $this->db->query('SELECT COUNT(*) FROM billets')->fetchColumn();
}
public function getList($debut = -1, $limite = -1)
{
$sql = 'SELECT id, titre, contenu, dateAjout, dateModif FROM billets ORDER BY id DESC';
if ($debut != -1 || $limite != -1)
{
$sql .= ' LIMIT '.(int) $limite.' OFFSET '.(int) $debut;
}
$q = $this->db->query($sql);
$q->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Billets');
$listeBillets = $q->fetch();
foreach ($listeBillets as $billets)
{
$billets->setDateAjout(new DateTime($billets->dateAjout()));
$billets->setDateModif(new DateTime($billets->dateModif()));
}
$q->closeCursor();
return $listeBillets;
}
public function getUnique($id)
{
$q = $this->db->prepare('SELECT id, titre, contenu, dateAjout, dateModif FROM billets WHERE id =:id');
$q->bindValue(':id', (int) $id, PDO::PARAM_INT);
$q->execute();
$q->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Billets');
$billets = $requete->fetch();
$billets->setDateAjout(new DateTime($billets->dateAjout()));
$billets->setDateModif(new DateTime($billets->dateModif()));
return $billets;
}
protected function update(Billets $billets)
{
$q = $this->db->prepare('UPDATE billets SET titre = :titre, contenu = :contenu, dateModif = NOW() WHERE id = :id');
$q->bindValue(':titre', $billets->titre());
$q->bindValue(':contenu', $billets->contenu());
$q->bindValue(':id', $billets->id(), PDO::PARAM_INT);
$q->execute();
}
public function save(Billets $billets)
{
if ($billets->isValid())
{
$billets->isNew() ? $this->add($billets) : $this->update($billets);
}
else
{
throw new RuntimeException('Le billet doit être valide pour être enregistré');
}
}
}
?> |
Partager