Reputation: 2393
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.
Upvotes: 19
Views: 32250
Reputation: 1062
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);
Upvotes: 71
Reputation: 1
If you use PDO then you should add the line use PDO
in the file where you are going to use the class PDO Ford example in file where you create object PDO and in each the file of model.
Upvotes: -1