【问题标题】:How to properly set up a PDO connection using anonymous function and closures如何使用匿名函数和闭包正确设置 PDO 连接
【发布时间】:2017-05-23 10:13:47
【问题描述】:

在类似主题Answer by "teresko" 的帖子的答案的帮助下,我设法了解了建立与我的数据库的连接的工厂设计方法。但是当我收到此错误时,我无法在我的代码中实现逻辑:

致命错误:在第 42 行的 C:\somewhere\db2.php 中找不到类 'conn'

这是我的数据库文件:

$provider = function() {
    $db_user="root"; // db user
    $db_password="";// db password (mention your db password here)
    $db_database="cl";// database name
    $db_host="localhost"; // db server

    $instance = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
    $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $instance;
};

$factory = new StructureFactory( $provider );
$conn = $factory->create('conn');

class StructureFactory {
   // protected $provider = null;
   protected $connection = null;

   public function __construct( callable $provider ) {
       $this->provider = $provider;
   }

   public function create($name) {
       if ( $this->connection == null ) {
           $this->connection = call_user_func( $this->provider );
       }
       return new $name($this->connection );
   }
}

由于我是新用户,我无法请求这个问题作为对原始答案的评论。请各位大神帮我看看哪里出错了?正如最初的问题所说,“我真的很想知道如何使用 PHP 和 PDO 正确连接到 MySQL 数据库并使其易于访问。我很想学习......”

【问题讨论】:

  • return new $name($this->connection ); 表示$name 是一个类,如果您希望PDO 对象替换为return $this->connection
  • 大家学习基于pdo的redbeanphp。
  • 感谢@cske 它对我有用.. :)

标签: php mysql pdo closures anonymous-function


【解决方案1】:

假设您是新用户,只需将其设为简单的 PDO 实例即可。

$db_user="root"; // db user
$db_password="";// db password (mention your db password here)
$db_database="cl";// database name
$db_host="localhost"; // db server
$db_charset="utf8";

$conn = new PDO("mysql:host=$db_host;dbname=$db_database;charset=$db_charset", $db_user, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

【讨论】:

  • 谢谢,但我试图设置一个配置文件,然后为每个数据库创建和维护一个可重用的连接。
  • 继续,把这段代码放在一个单独的文件中,然后直接包含它
猜你喜欢
  • 2012-07-07
  • 2016-09-09
  • 2011-12-25
  • 1970-01-01
  • 2013-02-21
  • 2019-12-24
  • 2017-01-11
  • 1970-01-01
相关资源
最近更新 更多