Files
LesRecettesDePapis/src/Domain/Repository.php

100 lines
3.0 KiB
PHP
Raw Normal View History

2026-04-02 16:33:32 +02:00
<?php
namespace App\Domain;
use App\Domain\Recettes\Recette;
use App\Kernel;
use PDO;
abstract class Repository {
/**
* Instancie des éléments de cette classe par rapport au repository.
* @return class-string
*/
abstract public static function getEntity(): string;
/**
* Doit retourner une liste du type :
* ['table' => '', 'columns' => [ ...Liste des colonnes dans la BDD ] ].
* @return array
*/
abstract public static function getStructure(): array;
final public string $tableName;
final public array $tableColumns;
public function __construct(){
$structure = static::getStructure();
$this->tableName = $structure['table'];
$this->tableColumns = $structure['columns'];
}
/**
* Permet d'avoir tous les éléments correspondant à la requête passée en paramètre.
*
* @param string $sqlQuery
* @return array|null
*/
public function selectGetAll( string $sqlQuery ): ?array {
$statement = Kernel::$DB->pdo->prepare( $sqlQuery );
if( !$statement->execute() )
return null;
$results = $statement->fetchAll( PDO::FETCH_CLASS, static::getEntity() );
if( empty( $results ) )
return null;
return $results;
}
public function addEntity( Model $entity ): bool {
$query = "INSERT INTO {$this->tableName} (";
$values = "(";
foreach( $this->tableColumns as $column ) {
$query .= "`{$column}`,";
$values .= ":{$column},";
}
$query = substr( $query, 0, -1 ) . ")";
$values = substr( $values, 0, -1 ) . ")";
$query .= " VALUES " . $values . ";";
$statement = Kernel::$DB->pdo->prepare( $query );
foreach( $this->tableColumns as $column ) {
$statement->bindValue(":{$column}", $entity->{$column} );
}
return $statement->execute();
}
public function updateEntity( Model $entity, string $identifier ): bool {
$query = "UPDATE {$this->tableName} SET ";
foreach( $this->tableColumns as $column ) {
$query .= "`{$column}` = :{$column},";
}
$query = substr( $query, 0, -1 ) . " WHERE {$identifier} = :{$identifier};";
$statement = Kernel::$DB->pdo->prepare( $query );
foreach( $this->tableColumns as $column ) {
$statement->bindValue(":{$column}", $entity->{$column} );
}
$statement->bindValue( ":{$identifier}", $entity->{$identifier} );
return $statement->execute();
}
public function deleteEntity( Model $entity, string $identifier ): bool {
$query = "DELETE FROM {$this->tableName} WHERE {$identifier} = :{$identifier};";
$statement = Kernel::$DB->pdo->prepare( $query );
$statement->bindValue( ":{$identifier}", $entity->{$identifier} );
return $statement->execute();
}
abstract public function add( Model $entity ): bool;
abstract public function update( Model $entity ): bool;
abstract public function delete( Model $entity ): bool;
}