Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespace PDO not found

I'm facing an issue I unfortunatly could not resolve so far. I created a database class into app/db/mysql/database.php with the following content :

<?php
    namespace App\Database;
    use Symfony\Component\Yaml\Yaml;

    class Database{
        private static $connection = null;

        private function __construct( $host, $base, $user, $pass ){
            try{
                self::$connection = new PDO("mysql:host=$host;dbname=$base", $user, $pass);
            }catch(PDOException $e){
                die($e->getMessage());
            }
        }

        public static function get(){
            if( self::$connection !== null ){
                return self::$connection;
            }
            $yaml = Yaml::parse(file_get_contents(realpath('./app') . '/database.yml'));
            self::$connection = new Database( $yaml['host'], $yaml['base'], $yaml['user'], $yaml['pass'] );
        }
    }

Using composer, I'm autoloading this class :

{
    "autoload" : {
        "classmap" : [
            "app/libraries",
            "app/db"
        ]
    }
}

Which generate an autoload_classmap.php such as :

return array(
    'App\\Database\\Database' => $baseDir . '/app/db/mysql/database.php',
    'App\\Libraries\\Parser' => $baseDir . '/app/libraries/Parser.php',
);

Now, when everything works fine, I'm always getting an error related to PDO :

Fatal error: Class 'App\Database\PDO' not found in /var/www/my_application/app/db/mysql/database.php on line 24

I think the problem comes from namespace because when I put the class into the index page, I don't have any error. PDO is installed and works.

like image 562
lkartono Avatar asked Oct 31 '13 05:10

lkartono


1 Answers

You should be using correct namespaces for the objects in your methods, either "use" them or prefix them with the root namespace;

<?php
//... namespace etc...

use \PDO;

self::$connection = new PDO("mysql:host=$host;dbname=$base", $user, $pass);
    

or simply;

self::$connection = new \PDO("mysql:host=$host;dbname=$base", $user, $pass);
like image 141
wtfzdotnet Avatar answered Oct 20 '22 08:10

wtfzdotnet