How to use namespace when creating a class?

Asked

Viewed 35 times

0

I’m working on a project that was created in php (5.3) without a framework. I need to use a database connection class I developed myself. The name of this class shall be db, but another class db already exists in the project. So to avoid conflicts I’ll use the namespace I’m creating.

I was looking at the documentation and it wasn’t very clear to me how I should use the path in namespace until my class. This is the structure I have on my website:

/
folder1/
folder2/
  file2.1.php
  file2.2.php
folder3/
classes/
  db.php
file1.php
file2.php
file3.php
includes/
  _antes.php

I would like to know how I do the name space of db.php.

That is correct?

namespace ../classes/

class db {
   ...
}

Note:

I’m using an autoloader on index.php which can load the class each time the object is called. (The autoloader code is in the class usage example)

EDITION

Your question has been identified as a possible duplicate of another question. If the answers there do not solve your problem, please edit to explain in detail the parts of your question that are different.

For the control staff you suggested resp1 and resp2 as a solution to my question.

These two answers show what they are and compare namespaces and autoloads. My question is "How do I use namespace in creating a class?" not "what are namespaces?".

Now updating my tests:

According to the directory tree above, I created the class db.php inside the Folder classes/. Inside the class I created the namespace like this namespace classes;

When I try to instantiate the class from within the _before.php file I have the following error in the browser:

Within 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

That is, I don’t know if the error is due to the way namespace was used in the class or if it was an error of how the class was called, giving the path to the namespace. Try using .. db; classes from within includes/_antes.php and it doesn’t work.

I still doubt.

End of update.

Although it won’t be necessary, I’ll leave the class to whomever I find useful:

<?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




>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • related: https://answall.com/questions/163660/namespace-com-php

  • You didn’t actually answer my question. The answers above explain what namespaces and autoloads are. My question concerns the composition of the namespace path - that is my question. From what I understand the path of the namespace is relative to the next higher Folder than the class and when I use this class I have to use root path to the place where the class is being instantiated. Doubt continues.

  • the duplicate and the other that is also duplicate explains this part of the path, But, you know what you could do is go to the finish line and explain that you don’t agree with the closure of this issue, because, for you, you still had doubts, I honestly don’t mind taking my vote of duplicate. Well I would do that ...

No answers

Browser other questions tagged

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