我试图创建一个工厂类以启动数据库连接,这样我只有一个数据库实例。
由于某种原因,工厂静态方法
的getInstance()
不想被叫,所以工厂没有被创造,我不能爱我,看看为什么它不会被召唤。这是我试图调用getInstance函数的引导程序:
require_once('app_config.php');
require_once('autoloader.php');
//Create new instance of PSR-O autoloader and register classes being used.
$classLoader = new SplClassLoader('App', SITE_ROOT);
$classLoader->register();
$factory = new App\Core\connectionFactory();
$dbh = $factory::getInstance()->getConnection();
$route = new App\Core\router();
$route->setDefaultController(DEFAULT_CONTROLLER);
$route->setDefaultMethod(DEFAULT_METHOD);
$route->do_route();
$controller = $route->getController();
$method = $route->getMethod();
$arguments = $route->getArgs();
$controller = 'App\\Frontend\\Base\\' . $controller . 'Controller';
$method = strtolower($method).'Method';
$controller = new $controller($dbh);
$controller->$method();
这是我的工厂类:
namespace App\Core;
class connectionFactory {
private static $instance = NULL;
private $db;
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function db_connect_details(){
$m_rdbms = 'mysql';
$m_host = 'localhost';
$m_db_name = 'cvcms';
$m_host_name = $m_rdbms . ':host=' . $m_host. ';dbname=' . $m_db_name;
$m_uname = 'root';
$m_pwd ='';
$m_arr_db_connect_details['hostname'] = $m_host_name;
$m_arr_db_connect_details['user_name'] = $m_uname;
$m_arr_db_connect_details['user_pwd'] = $m_pwd;
return $m_arr_db_connect_details;
}
public function getConnection() {
$sets = $this->db_connect_details();
$m_host_name = $sets['hostname'];
$m_user_name = $sets['user_name'];
$m_user_pwd = $sets['user_pwd'];
if (!$this->db)
$this->db = new \PDO($m_host_name, $m_user_name, $m_user_pwd);
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $this->db;
}
}
正如您所见,我实例化了一个新的connectionFactory类,然后尝试调用getInstance()静态函数,然后使用getConnection函数将连接存储到
中$ DBH
但我得到了这个错误:
致命错误:在第20行的E:\ Programs \ xampp \ htdocs \ CVCMS \ App \ Core \ bootstrap.php中调用未定义的方法App \ Core \ connectionFactory :: getInstance()
第一个问题 任何想法为什么我得到这个错误? 还有任何想法,我可以改善这些代码?看起来有点乱。
第二个问题 当我修复了这个错误时,最好的方法是将它传递给我的DAL模型,在那里我拥有所有查询和获取函数?
非常感谢
答案 0 :(得分:0)
好的只是快速拍摄(代码太多): 好像你正在创建一个connectionFactory实例(Keyword" new"):
$factory = new App\Core\connectionFactory();
$dbh = $factory::getInstance()->getConnection();
尝试:
$dbh = App\Core\connectionFactory::getInstance()->getConnection();