PHP PDO bağlantı kapsamı

1 Cevap php

Hey guys Ben pdo bulundu bağlantı sınıf var. Ben dosya dahil edilir sayfada bağlantı yöntemini arıyorum. Sorun işlevleri içinde $ conn değişkeni ben yöntemi (benimle çıplak ben OOP için çok yeni), kamu, ve kimse sonra her fonksiyonu küresel kullanan diğer zarif bir çözüm vardı merak ediyordum belirtildiği halde tanımlanmış olmasıdır . Herhangi bir öneri büyük takdir edilmektedir.

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 USED ON

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

1 Cevap

Daha sonra bu instaces çoğaltan gerekir, değil mi bağl PDO sınıfını taşıyan veritabanı sınıfı declarate olabilir. Ve tüm veritabanı işlemleri bu sınıf tarafından yapıyor olabilir. Ben cevap aradığınız ne demek.

Ama sen Ürün Fabrikası desen sadece PDO hadle sınıfını kullanarak, bkz. Birçok veritabanı konnektörleri motorlarını kullanmak istemediğinizde bu tasarım deseni olmadan PDO'nun altında normal bir tam veritabanı desteği sınıfını kullanabilirsiniz (bir işlevi queryies yürütme içerir) ve edebilirsiniz.