2010-05-24 119 views
0

嘿家伙我有一个连接类,我找到了pdo。我在包含该文件的页面上调用连接方法。问题是在函数内$ conn变量没有被定义,即使我声明方法是公开的(对我来说是裸机,我对OOP很陌生),我想知道是否有人有一个优雅的解决方案,然后在每个函数中使用全局。任何建议,非常感谢。php pdo连接范围

CONNECTION

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; 
    } 

} 

PAGE用在

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(); 

回答

0

可以declarate数据库类,你背着康恩PDO类,那么你不应该重复这个instaces。以及您可以通过此类进行的所有数据库操作。我的意思是我的答案就是你搜索的内容。

但我明白,你只在产品工厂模式中使用PDO hadle类。如果不想使用许多数据库连接器引擎,则可以使用PDO下的普通完整数据库支持类(包括从一个函数执行查询),并且不使用此设计模式。

+0

你可以给我看一个例子吗? – Scarface 2010-05-25 00:38:35

+0

@Scarface:下载TinyMVC框架并从插件文件db.PDO_MVC.php获取你有例子 – Svisstack 2010-05-25 09:01:02