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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With