Generic crud with phpoo and Pdo (no framework)

Asked

Viewed 345 times

0

I want to make a kind of Generic Crud and I implemented the function of Insert, I know that the way I did is not a better way to do it and I don’t want to use any kind of frameworks and so I would like help, tips.

What is causing me more confusion is how I will do a correct and efficient processing of the data before they are inserted/edited, I did a cleaning function but I know it is more like a "gambiarra"because I like to use php’s Filters and I’m not finding a way to use them very well with object orientation and in a generic way.

I saw that it has some topics similar to mine, but I could not find what I’m looking for.

Class students:

<?php
require_once 'crud.php';
require_once 'usuarios.php';
require_once 'conexao.php';

class Alunos extends Usuarios {

    private $matricula;
    private $curso;
    private $turma;
    private $dados_cadastrais;
    private $con;

    //Métodos
    public function cadastrarAluno($dados) {
        $verifica = $this->con->conectar()->prepare("SELECT * FROM usuarios WHERE email = :email");
        $verifica->bindValue(":email", $dados['email']);
        $verifica->execute();

        if ($verifica->rowCount() > 0) {
           return false;
        } else {
            $this->dados_cadastrais = $this->limpeza($dados);
            $sql = "INSERT INTO usuarios (nome, nomepai, nomemae, datanasc, naturalidade, nacionalidade, estadocivil, sexo, endereco, complemento, bairro, cidade, estado, cep, telefone, celular, celular2, email, cpf, rg, orgaoe, estadoe, datae, formacao, cursof, senha, nivel) values (:nome, :nomepai, :nomemae, :datanasc, :naturalidade, :nacionalidade, :estadocivil, :sexo, :endereco, :complemento, :bairro, :cidade, :estado, :cep, :telefone, :celular, :celular2, :email, :cpf, :rg, :orgaoe, :estadoe, :datae, :formacao, :cursof, :senha, :nivel)";

            $cadastro = new Crud();
            if($cadastro->cadastrar($sql, $this->dados_cadastrais)){
                 return true;
            }else {
                return false;
            }
        }
    }

    function limpeza($dados){
        foreach ($dados as $key => $valor) {
            if(($key == "cpf") || ($key == "rg")){
                $_POST[$key] = filter_var($this->limpaDoc($valor), FILTER_SANITIZE_STRING);
            }else if(($key == "data") || ($key == "datae") || ($key == "datanasc")){
                 $_POST[$key] = filter_var($this->formataDataEua($valor), FILTER_SANITIZE_STRING);
            }else if(($key == "senha")){
                 $_POST[$key] = filter_var(md5($valor), FILTER_SANITIZE_STRING);
            }else{
                $_POST[$key] = filter_var($valor, FILTER_SANITIZE_STRING);
            }    
        }

        return $dados;
    }

    function formataDataEua($data){
        $data = date("Y-m-d", strtotime(str_replace('/', '-', $data)));
        return $data;
    }

    function limpaDoc($valor) {
        $valor = preg_replace('#[^0-9]#', '', $valor);
        return $valor;
    }

    //Métodos especiais
    function __construct() {
        $this->nivel = 0;
        $this->con = new Conexao();
    }

Crud class

<?php
require_once 'conexao.php';
class Crud {

    private $con;
    private $insert;
    private $update;
    private $delete;

    //Métodos especiais
    function __construct() {
        $this->con = new Conexao();
    }

    function insert($sql, $dados) {
        $this->insert = $this->con->conectar()->prepare($sql);
        foreach ($dados as $key => $valor) {
            if(is_numeric($valor)){
                $this->insert->bindValue(":$key", $valor, PDO::PARAM_INT);
            }else{
                $this->insert->bindValue(":$key", $valor, PDO::PARAM_STR);
            }
        }
        if ($this->insert->execute()) {
            return true;
        } else {
            return false;
        }
    }

}
  • Well, this whole code is very gambiarra, so I can’t even help much, according to what you ask in the question the solution would be to start doing everything again. I will give the advice I always give and always ignore. Start at the basics, try to do the fundamental well and then think about OOP. Who knows find that OOP is not all this, there is more marketing on it than a real solution. It is even a solution to problems who ask for OOP, made by those who dominate very well. Most of the OOP codes I see would look much better without being OOP. Not least because they’re not even real OOP. This case.

  • 1

    As it is, I would check the data before consulting the email, otherwise there will always be a query. Second, the email query - whether you are registered or not - is also part of the CRUD, I didn’t see the point of separating like you did.

  • 1

    If your problem is validation, you don’t need a framework for that, just have a lib that you can implement. Laravel has an interesting validation in my opinion, and you can take as a basis.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.