Estou trabalhando num projeto que foi criado em php (5.3) sem nunhum framework.
Estou precisnado usar uma classe de conexão ao banco de dados que eu mesmo desenvolvi.
O nome dessa classe será db
, mas uma outra classe db
já existe no projeto.
Então para não haver conflitos vou usar o namespace na que estou criando.
Estava olhando a documentação e não ficou muito claro para mim como eu deveria usar o path no namespace até minha classe. Essa é a estrutura que tenho no meu site:
/
folder1/
folder2/
file2.1.php
file2.2.php
folder3/
classes/
db.php
file1.php
file2.php
file3.php
includes/
_antes.php
Gostaria de saber como faço o name space de db.php
.
Assim está correto?
namespace ../classes/
class db {
...
}
Nota:
Estou usando um autoloader no index.php
que pode carregar a classe cada vez que o objeto for chamado. (O código do autoloader está no exemplo de uso da classe)
EDIÇÂO
A sua pergunta foi identificada como possível duplicata de outra pergunta. Se as respostas ali não resolverem o seu problema, por favor edite para explicar em detalhe as partes da sua pergunta que são diferentes.
Para o pessoal do controle que sugeriu resp1 e resp2 como solução à minha pergunta.
Essas duas respostas mostram o que são e comparam namespaces e autoloads. A minha pergunta é "Como usar o namespace na criação de uma classe?" e não "o que são namespaces?".
Agora fazendo um update dos meus testes:
Segundo a árvore de diretórios acima, criei a classe db.php
dentro do folder classes/
. Dentro da classe criei o namespace assim namespace classes;
Quando tento instanciar a classe de dentro do arquivo _antes.php tenho o seguinte erro no browser:
Dentro de includes/_antes.php
use classes\db;
$db = new db();
Fatal error: Class 'classes\db' not found in C:\Users\myname\Documents\projects\mysite\public\includes\_antes.php on line 15
Ou seja, eu não sei se o erro é decorrente da maneira como namespace foi usado na classe ou se foi um erro de como a classe foi chamada, dando o path até o namespace. Tente usar use ..\classes\db; de dentro de includes/_antes.php e não funciona.
Continuo com dúvida.
Fim do update.
Embora não seja necessário, vou deixar a classe para quem achar útil:
<?php
/**
* Description of db
*
* @author zwitterion
*
* Throwing an Exception http://php.net/manual/en/language.exceptions.php
* Reference - http://coursesweb.net/php-mysql/pdo-exec-insert-update-delete
*/
class db {
public static $debugMode;
public static $dsn;
public static $username;
public static $password;
public static $db;
public static $conn;
public static $arrConnAttr; //Array of connection attributes. Ex: ["PDO::ATTR_ERRMODE", "PDO::ERRMODE_EXCEPTION"]
public static $pathLog; //Path to save the erro log files. Ex:$_SERVER['DOCUMENT_ROOT'] . "/myDirRootProject/LogError"
public static $arrCatchConnResult; //Results of the Catch process
public static $die; //If we set $setValues["die"]=NULL, during the object initialization, errors will not stop the process.
public static $sql; //Will store the sql string
/**
*
* @param array $setValues
* ex:<br>
* $setValues = [<br>
* "server" => "",<br>
* "dsn" => "",<br>
* "username" => "",<br>
* "password" => "",<br>
* "db" => "",<br>
* "arrConnAttr" => "",<br>
* "pathErroLog" => "",<br>
* "die" => "TRUE/FALSE",<br>
* "sql" => "",<br>
* "debugMode" => "TRUE/FALSE"<br>
* ]
*
* Ex:<br>
* $db = new db(["die"=>TRUE,"debugMode"=>TRUE]);
* $db = new db(["server"=>"1"]); Will search for server1 credentials
* $db = new db(["server"=>"2"]); Will search for server1 credentials
* or
* $db = new db(); Will connect to default server with default credentials
* $db = new db(["debugMode"=>TRUE]); If "debugMode"=>TRUE the die() (breaking process) will be sit to TRUE
*
*/
public function __construct(array $setValues = NULL) {
//Initialize the object
self::init($setValues);
try {
$dns = self::$dsn;
$username = self::$username;
$password = self::$password;
$db = self::$db;
self::$conn = new PDO("mysql:host=$dns; dbname=$db", "$username", "$password"); //Now private $conn is a PDO object
self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}// End of try
catch (PDOException $e) {//If had some error. The PDO object ($this->conn) could not be created. Throw an error.
self::$arrCatchConnResult = self::saveLogMsg(["exceptionObjc"=>$e,"sql"=>self::$sql]);
$msg = self::$arrCatchConnResult["displayMsgHTML"];
self::$conn = null;
if (self::$die) {
die($msg);
}
}
}
/**
*
* @param array $setValues
* ex:<br>
* $setValues = [<br>
* "server" => "",<br>
* "dsn" => "",<br>
* "username" => "",<br>
* "password" => "",<br>
* "db" => "",<br>
* "arrConnAttr" => "",<br>
* "pathErroLog" => "",<br>
* "die" => "TRUE/FALSE",<br>
* "sql" => "",<br>
* "debugMode" => "TRUE/FALSE"<br>
* ]
*
* Ex:<br>
* $db = new db(["die"=>TRUE,"debugMode"=>TRUE]);
* $db = new db(["server"=>"1"]); Will search for server1 credentials
* $db = new db(["server"=>"2"]); Will search for server1 credentials
* or
* $db = new db(); Will connect to default server with default credentials
* $db = new db(["debugMode"=>TRUE]); If "debugMode"=>TRUE the die() (breaking process) will be sit to TRUE
*
*/
private static function init(array $setValues=NULL) {
/*
* Variable array $arrInitDefault is used to initialize default values to the object;
* If array $setValues is not NULL its values should override the default values;
*/
#Default host credentials
$arrInitDefault["dsn"] = "defaultHost";
$arrInitDefault["username"] = "defaultUserName";
$arrInitDefault["password"] = "defaultPassword";
$arrInitDefault["db"] = "defaultDBname";
$arrInitDefault["arrConnAttr"] = ["PDO::ATTR_ERRMODE", " PDO::ERRMODE_EXCEPTION"];
$arrInitDefault["pathLog"] = dirname(__FILE__) . "/Log/Error"; //Default path to dir. Note: error pathLog can be "/Log/Error/UserName" or "/Log/Error/UserId", etc
$arrInitDefault["die"] = FALSE;//By default it will not break the web site, but will still generate the error file. $db = new db(["die"=>FALSE]);
$arrInitDefault["sql"] = FALSE;
$arrInitDefault["debugMode"] = FALSE;
//Catch dynamic sit values.
if (!is_null($setValues)) {
$arrInitDefault = array_merge($arrInitDefault, $setValues);
//If "debugMode"=True others debug variables must to be true.
if($arrInitDefault["debugMode"]){
$arrInitDefault["die"] = TRUE;
}
if(isset($setValues['server'])){
if($setValues['server']=="1"){
$arrInitDefault["dsn"] = "defaultHost";
$arrInitDefault["username"] = "defaultUserName";
$arrInitDefault["password"] = "defaultPassword";
$arrInitDefault["db"] = "defaultDBname";
}
elseif ($setValues['server']=="2") {
$arrInitDefault["dsn"] = "hostToServer2";
$arrInitDefault["username"] = "userNameServer2";
$arrInitDefault["password"] = "passwordServer2";
$arrInitDefault["db"] = "dbNameServer2";
}
}
}
//After merge, initialaze private variables with result merged $setValues
self::$dsn = $arrInitDefault["dsn"];
self::$username = $arrInitDefault["username"];
self::$password = $arrInitDefault["password"];
self::$db = $arrInitDefault["db"];
self::$arrConnAttr = implode(",", $arrInitDefault["arrConnAttr"]);
self::$pathLog = $arrInitDefault["pathLog"];
self::$sql = $arrInitDefault["sql"];
self::$die = $arrInitDefault["die"];
self::$debugMode = $arrInitDefault["debugMode"];
}
/**
* This function will save the logFile inside the LogFolder and will return an array with some messages
* @param array $saveLogsParam
* @return type array
*
* <br>
* That is the expected @param array:
* <br>
* $saveLogsParam = [<br>
* "sql" => "SELECT * FROM foo ..."<br>
* "exceptionObjc" => PDOException object #e<br>
* ]
* <br>
* That is the @return array:
* [<br>
* "status" => "The create message process status",<br>
* "msg" => "Some message about the status",<br>
* "displayMsgHTML" => "The message to be displayed in HTML format ...",<br>
* "displayMsgTXT" => ">>> ... the message to be displayed in TXT format ...",<br>
* ]
*
*/
public static function saveLogMsg($saveLogsParam = NULL) {
xdebug_break();
$year = date("Y");
$month = date("M");
$day = date("d");
$dt = date("d.M.Y_H.i.s");
$pathLog = self::$pathLog . "/" . $year . "/" . $month . "/" . $day . "/";
if (!is_dir($pathLog)) {
mkdir($pathLog, 0777, true);
}//If is not a dir, create it.
//Generate the HTML and .txt displayMessages trough self::getDisplayMessage($getDisplayMsgParam)
$getDisplayMsgParam = [
"dt" => $dt,
"exceptionObjc" => $saveLogsParam['exceptionObjc'],
"sql" => $saveLogsParam['sql']
];
$getDisplayMessage = self::getDisplayMessage($getDisplayMsgParam);
$createLogFile = [
"dt" => $dt,
"pathLog" => $pathLog,
"displayMsgTXT" => $getDisplayMessage['displayMsgTXT']
];
self::createLogFile($createLogFile);
return [
"status"=>TRUE,
"msg"=>"The folder $pathLog is sit!",
"displayMsgTXT"=>$getDisplayMessage['displayMsgTXT'],
"displayMsgHTML"=>$getDisplayMessage['displayMsgHTML']
];
}
/**
* This function will create the LogFile in a .txt format and store it in a specified $pathLog.
* @param array $param
*
* <br>
* That is the expected @param array:
* <br>
* $param = [<br>
* "dt" => "String - Displays date and time, like this - 28.apr.2017_18.5259",<br>
* "pathLog" => "String - The path where the log file will be stored.",<br>
* "displayMsgTXT" => "String - The key "displayMsgTXT" result from getDisplayMessage() method."<br>
* ]
*
*
*/
public static function createLogFile(array $param=NULL) {
if (!is_null($param)) {
$dt=$param["dt"];
$pathLog=$param["pathLog"];
$displayMsgTXT=$param["displayMsgTXT"];
$f = $pathLog . "$dt.txt";
if(self::$debugMode){
$myfile = fopen($f, "w") or die("Unable to open file!");
}
else {
$myfile = fopen($f, "w");//Will not stop the process even if we have a issue with the query process
}
fwrite($myfile, $displayMsgTXT);
fclose($myfile);
return
[
"status"=>TRUE,
"msg"=>"The file $myfile was successfully created!"
];
}
else {
return
[
"status"=>FALSE,
"msg"=>'Null $param was given to createLogFile() method'
];
}
}
/**
* @param array $param
* @return type array
*
* <br>
* That is the expected @param array:
* <br>
* $param = [<br>
* "dt" => "28.apr.2017_18.5259",<br>
* "exceptionObjc" => PDOException object #e,<br>
* "sql" => "SELECT * FROM foo ..."<br>
* ]
* <br>
* That is the @return array:
* [<br>
* "status" => "The create message process status",<br>
* "msg" => "Some message about the status",<br>
* "displayMsgHTML" => "The message to be displayed in HTML format ...",<br>
* "displayMsgTXT" => ">>> ... the message to be displayed in TXT format ...",<br>
* ]
*/
public static function getDisplayMessage(array $param=NULL) {
if (!is_null($param)) {
$excepObjc = $param['exceptionObjc'] ;
$logMsg = $excepObjc->getMessage();
$arrStackTrace=$excepObjc->getTrace();
$strTraceHTML="<table class='table'><thead></thead><tbody>";
$strTraceTXT=NULL;
foreach ($arrStackTrace as $k =>$arr) {
$strTraceHTML.="
<table class='table'>
<thead>
<th>Stack Trace [{$k}]</th>
</thead>
<tbody>
<tr>
<td>file</td><td>{$arr['file']}</td>
</tr>
<tr>
<td>line</td><td>{$arr['line']}</td>
</tr>
<tr>
<td>function</td><td>{$arr['function']}</td>
</tr>
</tbody>
</table>
";
$strTraceTXT.="
Gets the stack trace [{$k}]\n
file=>{$arr['file']}\n
line=>{$arr['line']}\n
function=>{$arr['function']}\n
";
}
$strTraceHTML.="</tbody></table>";
$displayMsgHTML = <<<EOF
<div class="alert alert-danger" role="alert">
Date: {$param["dt"]} <br/>
Msg: <span class="label label-danger">{$logMsg}</span><br/>
<kbd>Sql</kbd>: {$param["sql"]}<br/>
StackTrace: {$strTraceHTML}<br/>
</div>
EOF;
$displayMsgTXT = <<<EOF
>>>>> Log Message: <<<<< \n
Date:{$param["dt"]} \n
Msg: {$logMsg} \n
Sql: {$param["sql"]} \n
StackTrace: $strTraceTXT \n
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
EOF;
return
[
"status"=>TRUE,
"msg"=>'Display message was successfully created',
"displayMsgHTML"=>$displayMsgHTML,
"displayMsgTXT"=>$displayMsgTXT
];
}
else {
return
[
"status"=>FALSE,
"msg"=>'Null $param was given to getDisplayMessage() method',
"displayMsgHTML"=>$displayMsgHTML,
"displayMsgTXT"=>$displayMsgTXT
];
}
}
public static function get_values(array $setValues = NULL) {
try {
self::$sql = $setValues['sql'];
$stmt = self::$conn->prepare(self::$sql);
$stmt->execute();
while ($field = $stmt->fetch(PDO::FETCH_ASSOC)) {
$arrResult[] = $field;
}
return $arrResult;
}
catch (PDOException $e) {
self::$arrCatchConnResult = self::saveLogMsg(["exceptionObjc"=>$e,"sql"=>self::$sql]);
$msg = self::$arrCatchConnResult["displayMsgHTML"];
self::$conn = null;
if (self::$die) {
die($msg);
}
}
}
}
#How to use it?
#Use this autoload function to load the db Class when the db Object is instantieted.
#No need to use include or include once around the code!
spl_autoload_register(function ($class_name) {
include './classes/'.$class_name . '.php';
});
#Now lets instantiate an $db object
$db = new db();
#or
$db = new db(["die"=>TRUE,"debugMode"=>TRUE]);
#Performing a query
$setValues=[
"sql"=>"select * from myTablez",
];
$result = $db->get_values($setValues);
#If we have any error that is what we will see: in the Log Folder
>>>>> Log Message: <<<<<
Date:01.May.2017_19.21.24
Msg: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'hostpath.myTablez' doesn't exist
Sql: select * from myTablez
StackTrace:
Gets the stack trace [0]
file=>C:\Users\...\Documents\projects\...\public\classes\db.php
line=>371
function=>execute
Gets the stack trace [1]
file=>C:\Users\...\Documents\projects\...\public\includes\_before.php
line=>19
function=>get_values
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
path
, mas, sabe o que poderia fazer é ir para o meta e explicar que não concorda com o fechamento dessa questão, porque, pra você ainda ficou duvidas, eu sinceramente não importo em tirar o meu voto de duplicata. Bom eu faria isso ...