Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?
- abstract class conector{
- /**
- * Atributo que armazena o sistema de banco de dados utilizado
- *
- * @var string
- */
- private $sgbd='mysql';
- /**
- * Atributo que armazena o servidor aonde se localiza o nosso banco de dados
- *
- * @var string
- */
- private $servidor='localhost';
- /**
- * Atributo do sistema que armazena o usuario do banco de dados
- *
- * @var string
- */
- private $user;
- /**
- * Atributo que armazena a senha do banco de dados
- *
- * @var string
- */
- private $pass;
- /**
- * Atributo do sistema que armazena o banco de dados (schemata)
- *
- * @var string
- */
- private $bd;
- /**
- * Atributo do sistema que armazena o PDO
- *
- * @var PDO
- */
- private $PDO;
- private static $instance;
- private $errorMessage;
- private $debugLog=array();//
- const CONEXAO_BOTH=PDO::FETCH_BOTH;
- const CONEXAO_NUM=PDO::FETCH_NUM;
- const CONEXAO_ASSOC=PDO::FETCH_ASSOC;
- private function __construct($sgbd,$servidor,$usuario,$senha,$banco){
- $this->sgbd=$sgbd;
- $this->servidor=$servidor;
- $this->user=$usuario;
- $this->pass=$senha;
- $this->bd=$banco;
- try {
- $this->conectar();
- }catch(PDOException $e){
- throw $e;
- }
- }
- private function conectar(){
- try {
- $this->PDO=new PDO($this->sgbd.':dbname='.$this->bd.';host='.$this->servidor,$this->user,$this->pass);//Instanciando a classe do PDO
- } catch (PDOException $e) {
- //Excção por hora so joga pro proximo nivel
- throw $e;
- }
- }
- //Muda os parametros da conex�o criando uma nova sem recriar o objeto conector
- protected function changeConection(array $params){
- unset($this->PDO);
- if(!empty($params['bd']))$this->bd=$params['bd'];
- if(!empty($params['server']))$this->servidor=$params['server'];
- if(!empty($params['user']))$this->user=$params['user'];
- if(!empty($params['pass']))$this->pass=$params['pass'];
- if(!empty($params['sgbd']))$this->sgbd=$params['sgbd'];
- $this->conectar();
- }
- //Singleton DP
- protected function getInstance($sgbd,$servidor,$usuario,$senha,$banco){
- if(empty($instance)){
- return new conector($sgbd,$servidor,$usuario,$senha,$banco);
- }
- return $this->instance;
- }
- private function addToLog($method,$message){
- $str="Error at method :".$method." in ".date("Y-m-d H:i:s")." with message :".$message;
- $this->debugLog[]=$str;
- }
- /*
- *
- *
- * @return false
- * @return array
- * @param $camposSelecionar array
- * @param $tabela string
- * @param $whereStatement string
- * @param $limitMin int[optional]
- * @param $limitMax int[optional]
- * @param $tipoSelect int[optional]
- */
- protected function selecionar(array $camposSelecionar,$tabela,$whereStatement,$limitMin=null,$limitMax=null,$tipoSelect=PDO::FETCH_BOTH){
- //Começa a montagem dos campos que serão retornados pela busca
- $allowedComp=array('=','like','LIKE','>','<','>=','<=');
- $x=count($camposSelecionar);// Conta o números de elementos na array
- $limitData="";
- if($x===0){//Testa se não há elementos no array
- $strCamposSelecao='*'; //Determina que a busca deve ser de todos os campos
- }
- else{//Inicia a montagem da string dos campos passados pela array
- $strCamposSelecao='';
- $y=1;
- foreach($camposSelecionar as $campo){
- if($y<$x){
- $strCamposSelecao.='`'.$campo.'`,';
- }
- else{
- $strCamposSelecao.='`'.$campo.'`';
- }
- $y++;
- }
- }
- if(!empty($limitMin)){
- if(!empty($limitMax)){
- $limitData="LIMIT $limitMin,$limitMax";
- }else{
- $limitData="LIMIT $limitMin";
- }
- }
- try {
- $sqlSelecao="SELECT $strCamposSelecao FROM $tabela $whereStatement $limitData";//Monta a string do DML
- $res=$this->PDO->query($sqlSelecao)->fetch_all($tipoSelect);
- $numAffected=count($res);
- if($numLinhas===0){
- return false;
- }
- return $res;
- }
- catch(PDOException $e){
- throw $e;//Joga pro proximo nivel sempre
- }
- }
- /*
- * NOTA NA CLASSE QUE IMPLEMENTA O PARAMETRO WHERE E UMA STRING COM O TIPO E DEPOIS UM ARRAY ASSOCIATIVO COM OS PARAMETROS
- * DESSA FORMA EU PASSO O TIPO FAÇO UM SWITCH MONTO A CLÁUSULA WHERE E JOGO PRA CLASSE PAI QUE É ESSA.
- */
- protected function atualizar(array $campos,$tabela,$whereClause){
- //Monta os campos que terão valores inseridos
- $numCampos=count($campos);
- if($numCampos>=0){
- $campoAtual=1;
- $strCampo='';
- $strValor='';
- foreach($campos as $campo=>$valor){
- if($campoAtual===$numCampos){
- if((isset($valor) && $valor!=='' && !empty($valor)) || (int)$valor===0){
- $strCampo.="`".$campo."`='$valor'";
- }
- }
- else{
- if(isset($valor) && $valor!=='' && !empty($valor)){
- $strCampo.="`".$campo."`='$valor',";
- }
- }
- $campoAtual++;
- }
- }
- else{
- $this->addToLog("atualizar","inserção vazia");
- $this->errorMessage="Não é possível fazer uma inserção vazia";
- return false;
- }
- try{
- $sqlAtualiza="UPDATE $tabela SET $strCampo $whereClause";
- $insercao=$this->PDO->exec($sqlAtualiza);
- }catch(PDOException $e){
- $this->addToLog("atualizar",$e->getMessage());
- $this->errorMessage="Nao foi possivel atualizar o registro";
- return false;
- }
- if($insercao>=1){
- return true;
- }
- else{
- $erro=$banco->errorInfo();
- $this->addToLog("atualizar",$erro[2]);
- $this->errorMessage="Nao foi possivel atualizar o registro";
- return false;
- }
- }
- protected function inserir(array $campos, $tabela){
- //Monta os campos que terão valores inseridos
- $numCampos=count($campos);
- if($numCampos>=0){
- $campoAtual=0;
- $strCampo='';
- $strValor='';
- foreach($campos as $campo=>$valor){
- if($campoAtual===$numCampos){
- $strCampo.=$campo;
- $strValor.="'$valor'";
- }
- else{
- $strCampo.=$campo.',';
- $strValor.="'$valor',";
- }
- $campoAtual++;
- }
- }
- else{
- $this->errorMessage="Nao foi possivel inserir os campos poucos argumentos passados";
- $this->addToLog("inserir","Poucos argumentos");
- return false;
- }
- try{
- $insercao=$this->PDO->exec("Insert into $tabela ($strCampo) VALUES ($strValor)");
- }catch(PDOException $e){
- $this->addToLog("inserir",$e->getMessage());
- $this->errorMessage="Nao foi possivel realizar a inserção devido a query";
- return false;
- }
- if($insercao!=0){//Se o numero de affected rows>0
- return true;
- }
- else{
- $erro=$banco->errorInfo();
- $this->addToLog("inserir",$erro[2]);
- $this->errorMessage="Nao foi possivel realizar a inserção nenhum registro afetado";
- return false;
- }
- }
- protected function apagar($whereClause,$tabela,$limit=null){
- try{
- $sqlApaga="DELETE FROM $tabela $whereClause";
- if(empty($limit)===false && is_numeric($limit)){
- $sqlApaga.=" LIMIT $limit";
- }
- $apagar=$this->PDO->exec($sqlApaga);
- }catch(PDOException $e){
- $this->addToLog("apagar",$e->getMessage());
- $this->errorMessage="Nao foi possivel apagar o registro";
- return false;
- }
- if($apagar>=1){
- return true;
- }
- else{
- $erro=$banco->errorInfo();
- $this->addToLog("apagar",$erro[2]);
- $this->errorMessage="Erro ao Apagar Registro";
- return false;
- }
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement