【发布时间】:2014-05-13 19:12:36
【问题描述】:
我试图创建一个工厂类来启动数据库连接,这样我就只有一个数据库实例。
由于某种原因工厂静态方法
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 模型的最佳方法是什么?我拥有所有的查询和获取函数?
非常感谢
【问题讨论】:
-
工厂不是静态的。
-
只是想一想,既然可以
$factory->getConnection(),为什么还要getInstance -
@teresko,感谢您的输入,我一直在阅读它们,并且我到处都看到它们就是为什么我这样实现它,复制与我见过的其他结构相同的结构,所以我对你为什么这么说很感兴趣?谢谢
-
@Ejay,关于坚持工厂模式,我认为您必须首先获取工厂的实例,这样您就不会创建多个实例,因此 getInstance() 函数和那么您可以使用相同的实例使用 getConnection() 函数连接到数据库,因此只有一个与数据库的连接
-
我无法理解 this 工厂模式的实现。 (我还是新手,所以可能是时候自学了:))
标签: php singleton database-connection