0
I have some classes, I will post them to you can then explain my problem which is quite simple.
class connection to the database
<?php
/*
* Gerencia conexões com bancos de dados,
* usando arquivos de configuração
*/
/**
* Description of base_dao
*
* @author willian.rodrigues
*/
final class tconnection {
/*
* Não existirão instâncias de base_dao
* por isso marquei o contrutor como privado
*/
private function __construct() {
;
}
/**
* @param String $name Nome do banco de dados
* Verifica se exste arquivo de configuração para ele,
* e instancia o objeto PDO correspondente.
*/
public static function open($name = 'mysql_dgnetwork') {
try{
$option = array(
// mantem a conexão com o banco sempre aberta para o usuário
PDO::ATTR_PERSISTENT => true,
// define PDO::FETCH_ASSOC como padrão de retorno
PDO::ATTR_DEFAULT_FETCH_MODE => pdo::FETCH_ASSOC,
// define para que o PDO lance exceções na ocorrência de erros
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
/*
* Verifica se existe arquivo de configuração para ele
* e instancia o objeto PDO correspondente.
*/
if (file_exists("dao_config/{$name}.ini")) {
// lê o INI e retorna um array
$db = parse_ini_file("dao_config/{$name}.ini");
} else {
// se não existir, lança um erro
throw new Exception("Arquivo '$name' não encontrado");
}
// lê as informações contidas no arquivo
$user = isset($db['user']) ? $db['user'] : NULL;
$pass = isset($db['pass']) ? $db['pass'] : NULL;
$name = isset($db['name']) ? $db['name'] : NULL;
$host = isset($db['host']) ? $db['host'] : NULL;
$type = isset($db['type']) ? $db['type'] : NULL;
$port = isset($db['port']) ? $db['port'] : NULL;
/*
* Descobre qual o tipo do driver
* de banco de dados a ser utilizado.
*/
switch ($type) {
case 'mysql':
$port = $port ? $port : 3306;
$conn = new PDO("mysql:host={$host};port={$port};dbname={$name}", $user, "", $option);
// $conn = new PDO("mysql:host={$host};port={$port};dbname={$name}", $user, "");
break;
case 'pgsql':
$port = $port ? $port : 5432;
$conn = new PDO("pgsql:dbname={$name}; user={$user}; password={$pass}; host=$host;port={$port}");
break;
default :
throw Exception("Não foi possível conectar no banco de dados");
}
// retorna o atributo instanciado
return $conn;
} catch (PDOException $erro) {
// $mensagem = $erro->getMessage();
// //echo $mensagem;
// //SALVA NO ARQUIVO DE LOG O ERRO
// $dir = getcwd() . "/Logs//";
// error_log(date("Y-m-d H:i:s") . "|\n $mensagem|\r\n\r\n", 3, $dir . "DBconectionPDO.log");
} catch (Exception $erro) {
}
} // final do método open
}
base_dao
<?php
require_once '/xampp/htdocs/DGNetwork/model/persistence/dao/tconnection.class.php';
/**
* Description of base_dao
*
* @author willian.rodrigues
*/
abstract class base_dao {
// funções abstratos
abstract public function salvar(Object $obj);
// abstract public function deletar(Object $obj);
// abstract public function atualizar(Object $obj);
// abstract public function selecionar(Object $obj);
}
?>
a class that persists a vo - in this case I just want to select a
<?php
require_once '/xampp/htdocs/DGNetwork/model/persistence/dao/base_dao.class.php';
/**
* Description of estado_dao
*
* @author willian.rodrigues
*/
class estado_dao {
// construtor
public function __construct() {
echo 'Instancia de base_dao construida com sucesso';
}
// destrutor
public function __destruct() {
;
}
// funções
public function salvar(\Object $obj) {
// tabela estática
}
public function pesquisar($sigla) {
$sql = "SELECT * FROM estado WHERE sigla = ?";
// recupera uma referência de connection
$conn = tconnection::open();
// prepara a query
$query = $conn->prepare($sql);
// configura os parâmetros
$query->bindValue(1, $sigla);
// executa a query
$query->execute();
// acessa e retorna o resultado
$rs = $query->fetch();
return $rs;
}
public function pesquisar_all() {
$sql = "SELECT * FROM estado ORDER BY nome ASC";
// recupera uma referência de connection
$conn = tconnection::open();
print_r($conn);
// prepara a query
$query = $conn->prepare($sql);
// executa a query
$query->execute();
// acessa e retorna o resultado
$rs = $query->fetchAll();
return $rs;
}
}
//$e = new estado_dao();
//$estado = $e->pesquisar_all();
//
//foreach ($estado as $est) {
// echo $est['sigla'];
// echo '<br />';
// echo $est['nome'];
//}
note at the end of the above code, in the commented lines. If you decrement them, it searches n bank and displays in the bank the result normally.
now the class where the problem happens Here the problem, in my opinion is of scope. If anyone could help me, I’d be very grateful.
<?php
require_once '/xampp/htdocs/DGNetwork/model/persistence/dao/estado_dao.class.php';
/**
* Description of estado_service
*
* @author willian.rodrigues
*/
class estado_service {
// construtor
public function __construct() {
;
}
// destrutor
public function __destruct() {
;
}
/**
*
* @return array estado_vo
*/
public function get_all_estado() {
$estado_dao = new estado_dao();
$estado = $estado_dao->pesquisar_all();
return $estado;
}
}
$e = new estado_service();
$estado = $e->get_all_estado();
echo 'cheguei aqui';
foreach ($estado as $est) {
echo $est['sigla'];
echo $est['nome'];
}
in my browser, the following error appears:
Successfully built base_dao instance Fatal error: Call to a Member Function prepare() on a non-object in C: xampp htdocs Dgnetwork model persistence dao estado_dao.class.php on line 55
Could highlight the line of error?
– rray
Your status-dao class connection call is not being properly instantiated. However, there are several calls, as @rray suggested, indicate where the line 55 is, or within what method of the state_dao class.
– user28595
A tip is you always use in the classes, the pattern Camel Case, so your code becomes more legible.
– user28595
that’s right. public Function pesquisar_all() $query = $Conn->prepare($sql);
– willian rodrigues andrade
It seems $Conn should be within the scope of the service class.
– willian rodrigues andrade
If
$conn
is invalid the problem is intconnection::open();
. You have not declared any 'variable' as class member, they are all local method variables.– rray
I saw that you have already killed, the problem.
– willian rodrigues andrade
But will someone help me with a solution.
– willian rodrigues andrade
You need to check why the connection failed, can be incorrect user and password, incorrect database, port etc.
– rray
no friend. As I said above, the test on the DAO layer brought the data and displayed. The question was when I brought the text to the Service layer. If you notice the status code dao.class.php above, you will see the tests at the end, commented.
– willian rodrigues andrade
user8045 That’s right, it should be, but imagine, this using the 3-layer project pattern, where the controller talks with the service, the service with vo and with the DAO, Ai would not have Logia I bring it to the service, otherwise I would not do the DAO. My idea with this pattern is to leave the responsibilities very well defined. Please focus a little bit to help your friend here. hehehe God will give double for you.
– willian rodrigues andrade
@user8045 did not understand your last comment.
public function pesquisar_all() {
$sql = "SELECT * FROM estado ORDER BY nome ASC";
$conn = tconnection::open();
$query = $conn->prepare($sql);
if line 55 is$query = $conn->prepare($sql)
$conn
is not a PDO object.– rray
ta bom My stato_dao.class.php class works. At the end of it, from the stato_dao.class.php class, I ran a test. $e = new state_dao(); $status = $e->search_all(); foreach ($status as $est) { echo $est['acronym']; echo '<br />'; echo $['name']; } Ai worked as expected. It made me immediately think that the problem was related to the scope.
– willian rodrigues andrade
if the problem is scope then define namespaces and use an autoload method
– Marcelo Bonus
Hi Marcelo Bonus. I thought about it, but I don’t understand why I have to do it or how to do it. Can help me not
– willian rodrigues andrade