MagicFinder pour PDO
Posté : 19 juin 2010, 20:44
j'ai voulu tester la création de méthodes à la volé dans le style de Doctine, pour faire un test rapide j'ai juste étendu PDO. On fait ca grâce a la méthode magique __call, qui récupère la nom de la méthode appelé et les arguments.
la classe :
la classe :
class MagicFinder extends PDO
{
public function __call($name, array $arguments)
{
if(preg_match('/find(\w+)By(\w+)/u', $name, $matches))
{
$from = strtolower($matches[1]);
$col = strtolower($matches[2]);
return $this->find($from, $col, $arguments[0]);
}
}
public function find($from, $col, $search)
{
$sql = sprintf("SELECT * FROM `$from` WHERE `$col` = '%s'", $this->quote($search));
return $this->query($sql);
}
}
exemple de code d'utilisation :
$dbf = new MagicFinder('mysql:host=localhost;dbname=test', 'root');
$data = $dbf->findUserByCountry('france'); // find[le nom de la table]By[le nom du champ]
var_dump($data->fetchAll());