Created
March 29, 2019 16:02
-
-
Save ifranco88/825a5e36f72b6c36b49ed918c5cc85b4 to your computer and use it in GitHub Desktop.
A simple PDO Repository PHP Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$driver = 'mysql'; | |
$host = 'localhost'; | |
$dbname = 'dbname'; | |
$username = 'username'; | |
$password = 'password'; | |
$db = new PDO( | |
"{$driver}:host={$host};dbname={$dbname}", | |
$username, | |
$password | |
); | |
//Habilitar los errores de PDO | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$userRepository = new UserRepository($db); | |
$user = $userRepository->findById(1); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Carbon\Carbon; | |
use PDO; | |
/** | |
* Class PDORepository | |
*/ | |
abstract class PDORepository | |
{ | |
/** | |
* @var string | |
*/ | |
protected $tableName; | |
/** | |
* @var string | |
*/ | |
protected $keyColumn = 'id'; | |
/** | |
* @var PDO | |
*/ | |
private $pdo; | |
/** | |
* RepositoryBase constructor. | |
* @param PDO $pdo | |
*/ | |
public function __construct(PDO $pdo) | |
{ | |
$this->pdo = $pdo; | |
} | |
/** | |
* @return PDO | |
*/ | |
protected function db(){ | |
return $this->pdo; | |
} | |
/** | |
* @param $statement | |
* @param array $driver_options | |
* @return bool|\PDOStatement | |
*/ | |
protected function prepare($statement, array $driver_options = array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)){ | |
return $this->db()->prepare($statement, $driver_options); | |
} | |
/** | |
* @param $statement | |
* @param array $args | |
* @return mixed | |
*/ | |
protected function find($statement, array $args = array()){ | |
return $this->execute($statement, $args); | |
} | |
/** | |
* Recupera una fila filtrada por una columna especificada | |
* | |
* @param $value | |
* @param $col | |
* @return mixed | |
*/ | |
protected function findBy($value, $col){ | |
$query = "SELECT * FROM {$this->tableName} WHERE {$col} = ?"; | |
return $this->execute($query, [$value]); | |
} | |
/** | |
* Devuelve una row filtrada por Id/keyColumn | |
* | |
* @param $id | |
* @return mixed | |
*/ | |
public function findbyId($id){ | |
return $this->findBy($id, $this->keyColumn); | |
} | |
/** | |
* Recupera toas las filas fila filtrada por una columna especificada | |
* | |
* @param $value | |
* @param $col | |
* @return mixed | |
*/ | |
protected function findAllBy($value, $col){ | |
$query = "SELECT * FROM {$this->tableName} WHERE {$col} = ?"; | |
return $this->execute($query, [$value], false); | |
} | |
/** | |
* Inserta un nuevo registro con la información de los parámetros | |
* | |
* @param $params | |
* @return mixed | |
*/ | |
public function insert($params){ | |
$this->createTimestamp($params); | |
$this->updateTimestamp($params); | |
$columns = implode(',', array_keys($params)); | |
//Generamos el array con los argumentos preparados para ejecutar en PDO | |
$args = Array(); | |
foreach($params as $key => $value){ | |
$args[] = $value; | |
} | |
$valueBinds = substr(str_repeat('?,', count($args)), 0, -1); | |
$statement = "INSERT INTO {$this->tableName} ({$columns}) VALUES ({$valueBinds})"; | |
$query = $this->prepare($statement); | |
return $query->execute($args) ? $this->db()->lastInsertId() : FALSE; | |
} | |
/** | |
* Actualiza la información de los parámetros de un registro en concreto | |
* | |
* @param $val | |
* @param $params | |
* @return bool | |
*/ | |
public function update($val, $params){ | |
$this->updateTimestamp($params); | |
//Generamos el array con los argumentos preparados para ejecutar en PDO | |
$args = Array(); | |
$setData = Array(); | |
foreach($params as $key => $value){ | |
$args[] = $value; | |
$setData[] = "{$key} = ?"; | |
} | |
$args[] = $val; | |
$setString = implode(',', $setData); | |
$statement = "UPDATE {$this->tableName} SET {$setString} WHERE {$this->keyColumn} = ?"; | |
$query = $this->prepare($statement); | |
return $query->execute($args); | |
} | |
/** | |
* Elimina un registro indicado | |
* | |
* @param $val | |
* @return bool | |
*/ | |
public function remove($val){ | |
$args = Array($val); | |
$statement = "DELETE FROM {$this->tableName} WHERE {$this->keyColumn} = ?"; | |
$query = $this->prepare($statement); | |
return $query->execute($args); | |
} | |
/** | |
* @param $statement | |
* @param array $args | |
* @param bool $smart Devuelve un array si hay más de un row o la primera posición si sólo hay un reusltado. | |
* @return array|mixed | |
*/ | |
protected function execute($statement, array $args = array(), $smart = true){ | |
$query = $this->prepare($statement); | |
$query->execute($args); | |
$result = $query->fetchAll(PDO::FETCH_OBJ); | |
if($smart && $result and is_array($result) and count($result) == 1) return $result[0]; | |
else return $result; | |
} | |
/** | |
* Añade el timestamp de creación. | |
* | |
* @param $params | |
*/ | |
private function createTimestamp(&$params){ | |
$params['created_at'] = new Carbon(); | |
} | |
/** | |
* Añade el timestamp de actualización. | |
* | |
* @param $params | |
*/ | |
private function updateTimestamp(&$params){ | |
$params['updated_at'] = new Carbon(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class UserRepository | |
*/ | |
class UserRepository extends PDORepository | |
{ | |
/** | |
* @var string | |
*/ | |
protected $tableName = 'user'; | |
/** | |
* @var string | |
*/ | |
protected $keyColumn = 'user_id'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment