Entity Factories - ApinePHP/legacy-framework GitHub Wiki
A factory is a way to find and instantiate one or many entities from the database. It accesses to database to fetch corresponding data and build entities. The entity instanciation is directly lent to the entities so the factory only include the required methods to find and launch instantiations.
This feature requires prior knowledge of the Entity Model and Database Access
Factory Interface
The EntityFactoryInterface interface contains the list of the methods factories need to implement.
Entity Factories must implement these three methods :
static create_by_id(string $a_id) : EntityModel
Return an entity instantiated from the provided ID
static create_all() : Collection<Apine\Entity\EntityModel>
Return a collection of instantiated every entries
Sample Factory
use Apine\Entity\EntityFactoryInterface;
use Apine\Core\Database;
use Apine\Core\Collection;
use Apine\Modules\Sample\Sample;
class SampleFactory implements EntityFactoryInterface {
public static function is_id_exist ($entity_id) {
$id_sql = (new Database());
$id_sql = $database->select("SELECT `id` FROM `apine_samples` WHERE `id`=$entity_id");
if ($id_sql) {
return true;
}
return false;
}
public static function create_all () {
$database = new Database();
$request = $database->select('SELECT `id` from `apine_samples`');
$liste = new Collection();
if ($request != null && count($request) > 0) {
foreach ($request as $item) {
$liste->add_item(new Sample($item['id']));
}
}
return $liste;
}
public static function create_by_id ($a_id) {
$database = new Database();
$sql_id = $database->prepare('SELECT `id` FROM `apine_samples` WHERE `id`=?');
$ar_sql = $database->execute(array(
$a_id
), $sql_id);
if ($ar_sql) {
$return = new Sample($ar_sql[0]['id']);
} else {
$return = null;
}
return $return;
}
}