【问题标题】:php pdo connection scopephp pdo 连接范围
【发布时间】:2010-05-24 21:46:16
【问题描述】:

大家好,我为 pdo 找到了一个连接类。我在包含文件的页面上调用连接方法。问题是即使我声明该方法是公共的,在函数中 $conn 变量也没有定义,我想知道是否有人有一个优雅的解决方案,而不是在每个函数中使用全局。非常感谢任何建议。

连接

class PDOConnectionFactory{
    // receives the connection
    public $con = null;
    // swich database?
    public $dbType  = "mysql";

    // connection parameters
    // when it will not be necessary leaves blank only with the double quotations marks ""
    public $host    = "localhost";
    public $user    = "user";
    public $senha   = "password";
    public $db  = "database";

    // arrow the persistence of the connection
    public $persistent = false;

    // new PDOConnectionFactory( true ) <--- persistent connection
    // new PDOConnectionFactory()       <--- no persistent connection
    public function PDOConnectionFactory( $persistent=false ){
        // it verifies the persistence of the connection
        if( $persistent != false){ $this->persistent = true; }
    }

    public function getConnection(){
            try{
                // it carries through the connection
                $this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha, 
                array( PDO::ATTR_PERSISTENT => $this->persistent ) );
                // carried through successfully, it returns connected
                return $this->con;
            // in case that an error occurs, it returns the error;
            }catch ( PDOException $ex ){  echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }

    }

    // close connection
    public function Close(){
        if( $this->con != null )
            $this->con = null;
    }

}

页面使用时间

include("includes/connection.php");

$db = new PDOConnectionFactory();
$conn = $db->getConnection();

function test(){
try{
    $sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();

}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    你可以在你携带 conn pdo 类的地方声明数据库类,然后你不必重复这个实例。以及您可以通过此类进行的所有数据库操作。我的意思是我的答案就是你搜索的内容。

    但我明白了,您在产品工厂模式中仅使用 PDO hadle 类。当您不想使用许多数据库连接器引擎时,您可以在 PDO 下使用普通的完整数据库支持类(包括从一个函数执行查询)而无需此设计模式。

    【讨论】:

    • @Scarface:下载 TinyMVC 框架并从插件文件 db.PDO_MVC.php 获取示例
    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 2012-11-05
    • 1970-01-01
    • 2013-03-27
    • 2014-02-02
    • 2013-04-02
    • 2013-12-14
    • 2017-03-29
    相关资源
    最近更新 更多