Advertisement
Guest User

Untitled

a guest
May 7th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.12 KB | None | 0 0
  1. <?
  2. abstract class conector{
  3.     /**
  4.      * Atributo que armazena o sistema de banco de dados utilizado
  5.      *
  6.      * @var string
  7.      */
  8.     private $sgbd='mysql';
  9.     /**
  10.      * Atributo que armazena o servidor aonde se localiza o nosso banco de dados
  11.      *
  12.      * @var string
  13.      */
  14.     private $servidor='localhost';
  15.     /**
  16.      * Atributo do sistema que armazena o usuario do banco de dados
  17.      *
  18.      * @var string
  19.      */
  20.     private $user;
  21.     /**
  22.      * Atributo que armazena a senha do banco de dados
  23.      *
  24.      * @var string
  25.      */
  26.     private $pass;
  27.     /**
  28.      * Atributo do sistema que armazena o banco de dados (schemata)
  29.      *
  30.      * @var string
  31.      */
  32.     private $bd;
  33.     /**
  34.      * Atributo do sistema que armazena o PDO
  35.      *
  36.      * @var PDO
  37.      */
  38.     private $PDO;
  39.     private static $instance;
  40.     private $errorMessage;
  41.     private $debugLog=array();//
  42.     const CONEXAO_BOTH=PDO::FETCH_BOTH;
  43.     const CONEXAO_NUM=PDO::FETCH_NUM;
  44.     const CONEXAO_ASSOC=PDO::FETCH_ASSOC;
  45.     private function __construct($sgbd,$servidor,$usuario,$senha,$banco){
  46.         $this->sgbd=$sgbd;
  47.         $this->servidor=$servidor;
  48.         $this->user=$usuario;
  49.         $this->pass=$senha;
  50.         $this->bd=$banco;
  51.         try {
  52.             $this->conectar();
  53.         }catch(PDOException $e){
  54.             throw $e;
  55.         }
  56.     }
  57.     private function conectar(){
  58.         try {
  59.             $this->PDO=new PDO($this->sgbd.':dbname='.$this->bd.';host='.$this->servidor,$this->user,$this->pass);//Instanciando a classe do PDO
  60.         } catch (PDOException $e) {
  61.             //Excção por hora so joga pro proximo nivel
  62.             throw $e;
  63.         }
  64.            
  65.     }
  66.     //Muda os parametros da conex&#65533;o criando uma nova sem recriar o objeto conector
  67.     protected function changeConection(array $params){
  68.         unset($this->PDO);
  69.        
  70.         if(!empty($params['bd']))$this->bd=$params['bd'];
  71.         if(!empty($params['server']))$this->servidor=$params['server'];
  72.         if(!empty($params['user']))$this->user=$params['user'];
  73.         if(!empty($params['pass']))$this->pass=$params['pass'];
  74.         if(!empty($params['sgbd']))$this->sgbd=$params['sgbd'];
  75.        
  76.         $this->conectar();
  77.     }
  78.  
  79.     //Singleton DP
  80.     protected function getInstance($sgbd,$servidor,$usuario,$senha,$banco){
  81.         if(empty($instance)){
  82.             return new conector($sgbd,$servidor,$usuario,$senha,$banco);
  83.         }
  84.         return $this->instance;
  85.     }
  86.  
  87.     private function addToLog($method,$message){
  88.         $str="Error at method :".$method." in ".date("Y-m-d H:i:s")." with message :".$message;
  89.         $this->debugLog[]=$str;
  90.     }
  91.         /*
  92.      *
  93.      *
  94.      * @return false
  95.      * @return array
  96.      * @param $camposSelecionar array
  97.      * @param $tabela string
  98.      * @param $whereStatement string
  99.      * @param $limitMin int[optional]
  100.      * @param $limitMax int[optional]
  101.      * @param $tipoSelect int[optional]
  102.      */
  103.     protected function selecionar(array $camposSelecionar,$tabela,$whereStatement,$limitMin=null,$limitMax=null,$tipoSelect=PDO::FETCH_BOTH){
  104.         //Começa a montagem dos campos que serão retornados pela busca
  105.         $allowedComp=array('=','like','LIKE','>','<','>=','<=');
  106.         $x=count($camposSelecionar);// Conta o números de elementos na array
  107.         $limitData="";
  108.         if($x===0){//Testa se não há elementos no array
  109.             $strCamposSelecao='*';  //Determina que a busca deve ser de todos os campos
  110.         }
  111.         else{//Inicia a montagem da string dos campos passados pela array
  112.             $strCamposSelecao='';
  113.             $y=1;
  114.             foreach($camposSelecionar as $campo){
  115.                 if($y<$x){
  116.                     $strCamposSelecao.='`'.$campo.'`,';
  117.                 }
  118.                 else{
  119.                     $strCamposSelecao.='`'.$campo.'`';
  120.                 }
  121.                 $y++;
  122.             }
  123.                
  124.         }
  125.         if(!empty($limitMin)){
  126.             if(!empty($limitMax)){
  127.                 $limitData="LIMIT $limitMin,$limitMax";
  128.             }else{
  129.             $limitData="LIMIT $limitMin";
  130.             }
  131.         }
  132.         try {
  133.             $sqlSelecao="SELECT $strCamposSelecao FROM $tabela $whereStatement $limitData";//Monta a string do DML
  134.             $res=$this->PDO->query($sqlSelecao)->fetch_all($tipoSelect);
  135.             $numAffected=count($res);
  136.             if($numLinhas===0){
  137.                
  138.                 return false;
  139.             }
  140.             return $res;
  141.         }
  142.         catch(PDOException  $e){
  143.             throw $e;//Joga pro proximo nivel sempre
  144.         }
  145.     }
  146.     /*
  147.      * NOTA NA CLASSE QUE IMPLEMENTA O PARAMETRO WHERE E UMA STRING COM O TIPO E DEPOIS UM ARRAY ASSOCIATIVO COM OS PARAMETROS
  148.      * DESSA FORMA EU PASSO O TIPO FAÇO UM SWITCH MONTO A CLÁUSULA WHERE E JOGO PRA CLASSE PAI QUE É ESSA.
  149.      */
  150.     protected function atualizar(array $campos,$tabela,$whereClause){
  151.         //Monta os campos que terão valores inseridos
  152.         $numCampos=count($campos);
  153.  
  154.         if($numCampos>=0){
  155.             $campoAtual=1;
  156.             $strCampo='';
  157.             $strValor='';
  158.                
  159.             foreach($campos as $campo=>$valor){
  160.                 if($campoAtual===$numCampos){
  161.                     if((isset($valor) && $valor!=='' && !empty($valor)) || (int)$valor===0){
  162.                         $strCampo.="`".$campo."`='$valor'";
  163.                     }
  164.                 }
  165.                 else{
  166.                     if(isset($valor) && $valor!=='' && !empty($valor)){
  167.                            
  168.                         $strCampo.="`".$campo."`='$valor',";
  169.                     }
  170.                 }
  171.                 $campoAtual++;
  172.             }
  173.                
  174.         }
  175.         else{
  176.             $this->addToLog("atualizar","inserção vazia");
  177.             $this->errorMessage="Não é possível fazer uma inserção vazia";
  178.             return false;
  179.         }
  180.        
  181.         try{
  182.             $sqlAtualiza="UPDATE $tabela SET $strCampo $whereClause";
  183.             $insercao=$this->PDO->exec($sqlAtualiza);
  184.         }catch(PDOException $e){
  185.             $this->addToLog("atualizar",$e->getMessage());
  186.             $this->errorMessage="Nao foi possivel atualizar o registro";
  187.             return false;
  188.         }
  189.         if($insercao>=1){
  190.             return true;
  191.         }
  192.         else{
  193.             $erro=$banco->errorInfo();
  194.             $this->addToLog("atualizar",$erro[2]);
  195.             $this->errorMessage="Nao foi possivel atualizar o registro";
  196.             return false;
  197.         }
  198.     }
  199.     protected function inserir(array $campos, $tabela){
  200.         //Monta os campos que terão valores inseridos
  201.         $numCampos=count($campos);
  202.         if($numCampos>=0){
  203.             $campoAtual=0;
  204.             $strCampo='';
  205.             $strValor='';
  206.             foreach($campos as $campo=>$valor){
  207.                 if($campoAtual===$numCampos){
  208.                     $strCampo.=$campo;
  209.                     $strValor.="'$valor'";
  210.                 }
  211.                 else{
  212.                     $strCampo.=$campo.',';
  213.                     $strValor.="'$valor',";
  214.                 }
  215.                 $campoAtual++;
  216.             }
  217.         }
  218.         else{
  219.             $this->errorMessage="Nao foi possivel inserir os campos poucos argumentos passados";
  220.             $this->addToLog("inserir","Poucos argumentos");
  221.             return false;
  222.         }
  223.        
  224.         try{
  225.             $insercao=$this->PDO->exec("Insert into $tabela ($strCampo) VALUES ($strValor)");
  226.            
  227.         }catch(PDOException $e){
  228.             $this->addToLog("inserir",$e->getMessage());
  229.                 $this->errorMessage="Nao foi possivel realizar a inserção devido a query";
  230.             return false;
  231.         }
  232.         if($insercao!=0){//Se o numero de affected rows>0
  233.             return true;
  234.         }
  235.         else{
  236.             $erro=$banco->errorInfo();
  237.             $this->addToLog("inserir",$erro[2]);
  238.             $this->errorMessage="Nao foi possivel realizar a inserção nenhum registro afetado";
  239.            
  240.             return false;
  241.         }
  242.     }
  243.     protected function apagar($whereClause,$tabela,$limit=null){
  244.        
  245.         try{
  246.             $sqlApaga="DELETE FROM $tabela $whereClause";
  247.             if(empty($limit)===false && is_numeric($limit)){
  248.                 $sqlApaga.=" LIMIT $limit";
  249.             }
  250.             $apagar=$this->PDO->exec($sqlApaga);
  251.         }catch(PDOException $e){
  252.             $this->addToLog("apagar",$e->getMessage());
  253.             $this->errorMessage="Nao foi possivel apagar o registro";
  254.             return false;
  255.         }
  256.         if($apagar>=1){
  257.             return true;
  258.         }
  259.         else{
  260.             $erro=$banco->errorInfo();
  261.             $this->addToLog("apagar",$erro[2]);
  262.             $this->errorMessage="Erro ao Apagar Registro";
  263.             return false;
  264.         }
  265.     }
  266. }
  267.  
  268. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement