Namespace and PDO = Error

Asked

Viewed 1,345 times

4

I am making a Framework using namespaces. However in PDO connection file there is a strange error for me:

Fatal error: Uncaught Exception 'Pdoexception' with message 'could not find driver' in C: xampp htdocs Application Core Controller.php:36 Stack trace: #0 C: xampp htdocs Application Core Controller.php(36): PDO->__Construct('DB_TYPE:host=DB...', 'DB_USER', 'DB_PASS', Array) #1 C: xampp htdocs Application Core Controller.php(20): Application Core Controller->openDatabaseConnection() #2 C: xampp htdocs Public index.php(9): Application Core Controller->__Construct() #3 {main} thrown in C: xampp htdocs Application Core Controller.php on line 36

Index:

<?php

define('ROOT', dirname(__DIR__) . DIRECTORY_SEPARATOR);
require_once 'autoload.php';

use Application\Core\Application;
use Application\Core\Controller;

$controller = new Controller;

Autoload:

function __autoload($class) {
$class = ROOT . str_replace('\\', DIRECTORY_SEPARATOR, $class). '.php';
if(!file_exists($class)) {
    throw new Exception("File path '{$class}' not found.");
} else {
    require $class;
}
}

Controller

<?php
namespace Application\Core;
use PDO;

class Controller
{
/**
 * @var null Database Connection
 */
public $db = null;
/**
 * @var null Model
 */
public $model = null;
/**
 * Whenever controller is created, open a database connection too and load "the model".
 */
function __construct()
{
    $this->openDatabaseConnection();
    $this->loadModel();
    echo 'Loaded Controller <br/>';
}
/**
 * Open the database connection with the credentials from application/config/config.php
 */
private function openDatabaseConnection()
{
    // set the (optional) options of the PDO connection. in this case, we set the fetch mode to
    // "objects", which means all results will be objects, like this: $result->user_name !
    // For example, fetch mode FETCH_ASSOC would return results like this: $result["user_name] !
    // @see http://www.php.net/manual/en/pdostatement.fetch.php
    $options = array(\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_OBJ, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING);
    // generate a database connection, using the PDO connector
    // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
    $this->db = new \PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS, $options);
}
/**
 * Loads the "model".
 * @return object model
 */
public function loadModel()
{
    require APP . 'model/model.php';
    // create new "model" (and pass the database connection)
    $this->model = new Model($this->db);
}
}
  • 1

    Line 32 seems to be the variable $options..., missed the '\' backslash.

  • Or add below namespace, use PDO;

  • I changed the code but now you have another error.

  • 1

    No use put "use PDO";

1 answer

8


Just a correction in the código, place the instance of PDO inside the block try/catch

try {

} catch (\PDOException $e) {

}

Excerpt from the code

private function openDatabaseConnection()
{

    try {

        // set the (optional) options of the PDO connection. in this case, we set the fetch mode to
        // "objects", which means all results will be objects, like this: $result->user_name !
        // For example, fetch mode FETCH_ASSOC would return results like this: $result["user_name] !
        // @see http://www.php.net/manual/en/pdostatement.fetch.php
        $options = array(\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_OBJ, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING);
        // generate a database connection, using the PDO connector
        // @see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
        $this->db = new \PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS, $options);


    } catch (\PDOException $e) {

        echo 'Error:'. $e->getMessage();

    }

}

To use native functions with namespace calling, use a counter bar before the class or function name, or import using the operator use

Example:

<?php

namespace Application\Core;

use \PDO;
use PDOException;

//outras Exceptions
use Exception;
use InvalidArgumentException;

class Controller
{
   ...

Or use contra barra \ within the métodos

Ending

<?php
namespace Application\Core;

use \PDO;
use PDOException;

class Controller
{
    /**
     * @var null Database Connection
     */
    public $db = null;
    /**
     * @var null Model
     */
    public $model = null;
    /**
     * Whenever controller is created, open a database connection too and load "the model".
     */
    function __construct()
    {
        $this->openDatabaseConnection();
        $this->loadModel();
        echo 'Loaded Controller <br/>';
    }
    /**
     * Open the database connection with the credentials from application/config/config.php
     */
    private function openDatabaseConnection()
    {

        try {

            $options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
            $this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS, $options);        

        } catch (PDOException $e) {

            echo 'Error:'. $e->getMessage();

        }

    }
    /**
     * Loads the "model".
     * @return object model
     */
    public function loadModel()
    {
        require APP . 'model/model.php';
        // create new "model" (and pass the database connection)
        $this->model = new Model($this->db);
    }
}

Browser other questions tagged

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