Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Boa noite pessoal, uns tempos atrás eu postei o meu CRUD utilizando PDO, porém ficou gambiarra. No entanto, melhorei ele de uns dias pra cá e venho compartilhar com vocês. Críticas são SEMPRE bem-vindas!
O exemplo será do CRUD do Cliente.
config.php
<?
require_once ("DAO.php");
require_once ("Funcoes.php");
session_start();
error_reporting(E_ALL);
define("TB_CLIENTE","clientes");
?>
DAO.php
<?
class DAO extends PDO{
public $id;
public $tabela;
public $campos;
public $valores;
public $where;
public $limit;
public $asc;
public $desc;
public $data;
public $tabela1;
public $tabela2;
public $campo;
public $like;
private $connect;
private $root;
private $pass;
private static $conn;
function DAO($connect, $root = '', $pass = '') {
parent::__construct($connect, $root, $pass);
}
public static function getDAO() {
if (!isset(self::$conn)) {
try {
self::$conn = new DAO("mysql:host=localhost;dbname=jogosonline", "root", "");
}
catch (PDOException $e) {
throw new Exception("Erro ao conectar: " .$e->getMessage() . " Código: " .$e->getCode());
}
}
return self::$conn;
}
public static function PDO($sql) {
try {
self::$conn = DAO::getDAO();
$stm = self::$conn->prepare($sql);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
if (!empty($result)){
return $result;
}else{
return array();
}
}catch (PDOException $e) {
echo "Erro de exceção: ".$e->getMessage(). " Código: " .$e->getCode();
}
}
public function setId($id){
$this->id = $id;
}
public function getId(){
return $this->id;
}
public function select(){
$date = (!empty($this->data) ? ", DATE_FORMAT({$this->data}, '%d/%m/%Y') AS data" : "");
$padrao = (!empty($this->desc) ? "{$this->desc} DESC" : "{$this->asc} ASC");
$where = (!empty($this->where) ? "WHERE {$this->where}" : "" );
$limit = (!empty($this->limit) ? "LIMIT {$this->limit}" : "" );
$like = (!empty($this->like) ? "LIKE '%{$this->like}%'" : "" );
if((!empty($this->tabela1)) and (!empty($this->tabela2) and (!empty($this->campo)))){
$sql = "SELECT {$this->campos} {$date} FROM {$this->tabela1} INNER JOIN {$this->tabela2} ON {$this->campo} {$where} {$limit}";
}else{
$sql = "SELECT {$this->campos} {$date} FROM {$this->tabela} {$like} {$where} ORDER BY {$padrao} {$limit}";
}
return self::PDO($sql);
}
public function insert(){
$sql = "INSERT INTO {$this->tabela} ({$this->campos}) VALUES ({$this->valores})";
return self::PDO($sql);
}
public function update(){
$sql = "UPDATE {$this->tabela} SET {$this->campos} WHERE id = {$this->getId()}";
return self::PDO($sql);
}
public function delete(){
$sql = "DELETE FROM {$this->tabela} WHERE id = {$this->getId()}";
return self::PDO($sql);
}
public function total(){
$sql = "SELECT COUNT(*) AS total FROM {$this->tabela}";
return self::PDO($sql);
}
}
?>
Cliente.model.php
<?
class Cliente_Model{
private $nome;
private $email;
private $senha;
private $endereco;
private $telefone;
private $dataCadastro;
public function setNome($nome){
$this->nome = $nome;
}
public function setEmail($email){
$this->email = $email;
}
public function setSenha($senha){
$this->senha = $senha;
}
public function setEndereco($endereco){
$this->endereco = $endereco;
}
public function setTelefone($telefone){
$this->telefone = $telefone;
}
public function setDataCadastro($dataCadastro){
$this->dataCadastro = $dataCadastro;
}
public function getNome(){
return $this->nome;
}
public function getEmail(){
return $this->email;
}
public function getSenha(){
return $this->senha;
}
public function getTelefone(){
return $this->telefone;
}
public function getEndereco(){
return $this->endereco;
}
public function getDataCadastro(){
return $this->dataCadastro;
}
}
?>
Cliente.controller.php
<?
require_once ("../model/Cliente.model.php");
require_once ("../../config.php");
class Cliente_Controller extends DAO{
private $cliente;
private $controller;
function __construct(){
$this->cliente = new Cliente_Model();
$this->funcoes = new Funcoes();
}
public function actionCadastrar(){
$this->cliente->setNome($_POST['nome']);
$this->cliente->setEmail("gpn_90@hotmail.com");
$this->cliente->setSenha(md5($this->funcoes->geraSenha(10)));
$this->cliente->setEndereco($_POST['endereco']);
$this->cliente->setTelefone($_POST['telefone']);
$this->cliente->setDataCadastro(date("d/m/Y H:i:s"));
$this->tabela = TB_CLIENTE;
$this->campos = "nome, email, senha, endereco, telefone, dataCadastro";
$this->valores = "
'".$this->cliente->getNome()."',
'".$this->cliente->getEmail()."',
'".$this->cliente->getSenha()."',
'".$this->cliente->getEndereco()."',
'".$this->cliente->getTelefone()."',
".$this->cliente->getDataCadastro()."
";
$this->insert();
}
public function actionAtualizar(){
$this->cliente->setNome($_POST['nome']);
$this->cliente->setEmail($_POST['email']);
$this->cliente->setSenha(md5($_POST['senha']));
$this->cliente->setEndereco($_POST['endereco']);
$this->cliente->setTelefone($_POST['telefone']);
$this->tabela = TB_CLIENTE;
$this->campos = "
nome = '".$this->cliente->getNome()."',
email = '".$this->cliente->getEmail()."',
senha = '".$this->cliente->getSenha()."',
endereco = '".$this->cliente->getEndereco()."'
telefone = '".$this->cliente->getTelefone()."'
";
$this->update();
}
public function actionListar(){
$this->tabela = TB_CLIENTE;
$this->data = "cadastro";
$this->campos = "nome, email, endereco, telefone";
$this->asc = "nome";
$this->limit = 20;
$this->select();
$this->total();
}
public function actionBusca(){
$this->tabela = TB_CLIENTE;
$this->campos = "*";
$this->asc = "email";
$this->where = "nome";
$this->like = $_POST['busca'];
$this->limit = 20;
$this->select();
$this->total();
}
public function actionDeletar(){
$this->setId($_POST['id']);
$this->tabela = TB_CLIENTE;
$this->update();
}
}
?>
Funcoes.php
<?
class Funcoes{
public function gerarSenha($quantidade){
for($i = 0; $i < $quantidade; $i++){
return rand(1, $quantidade);
}
}
}
?>
Bom pessoal, espero ter ajudado em algo. Poste seus comentários e digam sua análise do código!
Grande abraço.
Então,
os métodos actionAtualizar(), actionBusca() e actionDeletar() usam da variável global $_POST, eu posso apenas fazer assim?
if(isset($_POST['enviar'])){
//instancio a classe controller
$cliente = new Cliente_Controller();
$cliente->actionCadastrar();
}
Aguardo
Opa, vou usar aqui, te retorno qualquer coisa.