Connexion à la base (Le Singleton SPDO)
Ce fichier permet d'obtenir une instance unique de connexion à la base de données.
PHP
// system/SPDO.php
namespace system;
class SPDO {
private \PDO $connexion;
private static ?SPDO $PDOInstance = null;
private function __construct(string $dsn, ?string $user, ?string $pass, ?array $opt, ?string $exec) {
$this->connexion = new \PDO($dsn, $user, $pass, $opt);
$this->connexion->exec($exec);
}
public static function getInstance($dsn, $user=null, $pass=null, $opt=null, $exec=null): \system\SPDO {
if(!self::$PDOInstance) {
self::$PDOInstance = new \system\SPDO($dsn, $user, $pass, $opt, $exec);
}
return self::$PDOInstance;
}
public function getConnexion(): \PDO {
return $this->connexion;
}
}
2. Le Modèle (Model)
L'Entité Produit
C'est une classe simple avec des attributs privés et des getters/setters.
PHP
// app/model/entity/ProductEntity.php
namespace app\model\entity;
class ProductEntity {
private int $id;
private string $name;
private float $price;
private int $quantity;
public function getId(): int { return $this->id; }
public function getName(): string { return $this->name; }
public function setName(string $name): void { $this->name = $name; }
// ... (autres getters et setters similaires)
}
Le Repository de Données (DB)
C'est ici que tu écris tes requêtes SQL préparées pour interagir avec madb.db.
PHP
// app/model/repository/DbProductRepository.php
namespace app\model\repository;
use PDO;
class DbProductRepository implements ProductRepositoryInterface {
private $connexion;
public function __construct() {
$dsn = "sqlite:".CFG["db"]["host"].CFG["db"]["database"];
$this->connexion = \system\SPDO::getInstance($dsn, CFG["db"]["login"], CFG["db"]["password"], CFG["db"]["options"], CFG["db"]["exec"])->getConnexion();
}
public function findAll(): array {
$stmt = $this->connexion->prepare("SELECT * FROM product");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_CLASS, "app\model\entity\ProductEntity");
}
public function findById(int $id): ?\app\model\entity\ProductEntity {
$stmt = $this->connexion->prepare("SELECT * FROM product WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_CLASS, "app\model\entity\ProductEntity");
return $stmt->fetch() ?: null;
}
public function update(int $id, \app\model\entity\ProductEntity $product): ?\app\model\entity\ProductEntity {
$stmt = $this->connexion->prepare("UPDATE product SET name=:name, price=:price, quantity=:qty WHERE id=:id");
$stmt->execute([
'name' => $product->getName(),
'price' => $product->getPrice(),
'qty' => $product->getQuantity(),
'id' => $id
]);
return $this->findById($id);
}
}