Hace tiempo he estado trabajando con JAVA y una vez que regreso a PHP quiero intentar seguir las mejores practicas en cuanto al uso de objetos, por lo cual quiero dedicar dicho post al uso de objetos en nuestro PDO para tener todo nuestro código y procesos de una forma más limpia.
Bueno para comenzar supongamos que haremos un modulo de «Usuarios» , lo primero que vamos a crear es una clase llamada User la cual tendra sus atributos : id_user,name,usr,psw, etc… y sus metodos getters y setters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
<?php class User { public $id_user; public $name; public $usr; public $psw; public $date_register; public $status; public $photo; public $permission; public function __construct() { } /** * @return mixed */ public function getIdUser() { return $this->id_user; } /** * @param mixed $id_user * * @return self */ public function setIdUser($id_user) { $this->id_user = $id_user; return $this; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name * * @return self */ public function setName($name) { $this->name = $name; return $this; } /** * @return mixed */ public function getUsr() { return $this->usr; } /** * @param mixed $usr * * @return self */ public function setUsr($usr) { $this->usr = $usr; return $this; } /** * @return mixed */ public function getPsw() { return $this->psw; } /** * @param mixed $psw * * @return self */ public function setPsw($psw) { $this->psw = $psw; return $this; } /** * @return mixed */ public function getDateRegister() { return $this->date_register; } /** * @param mixed $date_register * * @return self */ public function setDateRegister($date_register) { $this->date_register = $date_register; return $this; } /** * @return mixed */ public function getStatus() { return $this->status; } /** * @param mixed $status * * @return self */ public function setStatus($status) { $this->status = $status; return $this; } /** * @return mixed */ public function getPhoto() { return $this->photo; } /** * @param mixed $photo * * @return self */ public function setPhoto($photo) { $this->photo = $photo; return $this; } /** * @return mixed */ public function getPermission() { return $this->permission; } /** * @param mixed $permission * * @return self */ public function setPermission($permission) { $this->permission = $permission; return $this; } } ?> |
Posteriormente vamos a desarrollar una clase donde podríamos tener métodos básicos para nuestro modulo CRUD; getUsers, getUsersById, saveUser, etc…
Dentro de nuestra clase podemos heredar de la clase User para su posterior uso en ella, de está forma se me hizo mas sencillo la manipulación de nuestra clase «User» .
Fuera de nuestro código yo uso una clase llamada Connection la cual tiene los parámetros de conexión a nuestra base de datos.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
<?php require '../src/Bean/User.php'; class MethosUser extends User{ private $conn; public function __construct() { require '../src/Configuration/Connection.php'; $this->conn = new Connection(); } public function login($user,$psw) { try { $sql = "SELECT * FROM USER AS US WHERE US.status=1 AND US.user='$user' AND US.psw='$psw';"; $db = $this->conn->getConnection(); $stmt = $db->query($sql); $rs = $stmt->fetchAll(PDO::FETCH_CLASS, "User"); $db = null; return count($rs)>0 ? $rs : []; } catch(PDOException $e) { return '{"error":{"text":'. $e->getMessage() .'}}'; } } public function resetPsw($id_user,$tmpPsw) { try { $sql = "UPDATE USER SET PSW='$tmpPsw' WHERE ID_USER = $id_user"; $db = $this->conn->getConnection(); $stmt = $db->prepare($sql); $stmt->execute(); $response = $stmt->rowCount() ? 1 : 0; return $response; } catch(PDOException $e) { return '{"error":{"text":'. $e->getMessage() .'}}'; } } public function getUsers() { try { $sql = "SELECT * FROM USER AS US WHERE US.STATUS=1"; $db = $this->conn->getConnection(); $stmt = $db->query($sql); $rs = $stmt->fetchAll(PDO::FETCH_CLASS, "User"); $db = null; return $rs; } catch(PDOException $e) { return '{"error":{"text":'. $e->getMessage() .'}}'; } } public function getUsersById($id_user) { try { $sql = "SELECT * FROM USER AS US WHERE US.ID_USER=$id_user"; $db = $this->conn->getConnection(); $stmt = $db->query($sql); $rs = $stmt->fetchAll(PDO::FETCH_CLASS, "User"); $db = null; return $rs; } catch(PDOException $e) { return '{"error":{"text":'. $e->getMessage() .'}}'; } } public function saveUser(User $user) { $sql = "INSERT INTO user(`name`,`user`,`psw`,`date_register`,`status`,`photo`,`permission`) VALUES (:name,:user,:psw,:date_register,:status,:photo,:permission)"; try { $db = $this->conn->getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $user->getName()); $stmt->bindParam("user", $user->getUsr()); $stmt->bindParam("psw", sha1($user->getPsw()) ); $stmt->bindParam("date_register", $user->getDateRegister()); $stmt->bindParam("status", $user->getStatus()); $stmt->bindParam("photo", $user->getPhoto()); $stmt->bindParam("permission", $user->getPermission()); $stmt->execute(); $id = $db->lastInsertId(); $response = $id > 0 ? $id : 0; $db = null; return $response; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } public function editUser(User $user) { $sql = "UPDATE user SET `user` = :user:, `psw` = :psw:, `date_register` = :date_register:, `status` = :status:, `photo` = :photo:, `permission` = :permission> WHERE `id_user` = :id_user"; try { $db = $this->conn->getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("id_user", $user->getIdUser()); $stmt->bindParam("name", $user->getName()); $stmt->bindParam("user", $user->getUsr()); $stmt->bindParam("psw", $user->getPsw()); $stmt->bindParam("date_register", $user->getDateRegister()); $stmt->bindParam("status", $user->getStatus()); $stmt->bindParam("photo", $user->getPhoto()); $stmt->bindParam("permission", $user->getPermission()); $stmt->execute(); $response = $stmt->rowCount() ? 1 : 0; $db = null; return $response; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } public function deleteUser(User $user) { $sql = "DELETE FROM `user` WHERE id_user=:id_user"; try { $db = $this->conn->getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("id_user", $user->getIdUser()); $stmt->execute(); $response = $stmt->rowCount() ? 1 : 0; $db = null; return $response; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } } } ?> |
Como observamos en los métodos se utiliza dos procesos de PDO muy importantes :
1 – PDO::FETCH_CLASS, «User» : el cual le pasamos de parámetro «User» que por ende esto va enlazado a nuestra clase User, el pdo automáticamente tomara los atributos declarados dentro de nuestra clas User. si en un futuro se agrega un nuevo campo a nuestra base de datos, basta con agregarlo SOLAMENTE a nuestra clase User.
2 – $stmt->bindParam(«name», $user->getName()); donde el primer parametro es el nombre del campo en la Base de Datos, y el segundo es el valor asignamos en la clase User.
Con este sencillo ejemplo concluimos el uso de objetos con PDO, si tienen algún aporte o comentario sobre como podríamos mejorar nuestro código y usarlo de una mejor forma con gusto me gustaría saberlos.