Best way to make a PDO mysql static connection class?
Asked Answered
O

2

8

I'm quite new to PDO and also OOP with PHP in general so please be nice :) Basically I'm trying to make a connection object based on PDO so that I can have one connection that I call throughout my site.

I need some prepared statements that simply look up different results based on an ID I pass through using the same db object that I'm trying to create below.

How do I make and access the db class I set below and then use functions within it to extract the relevant info I need? Any examples would be great so I can get an idea of the best practices etc.

Many thanks in advance.

class db {

    private static $connection;

    private function __construct(){}
    private function __clone(){}

    private static function connect($db_server="localhost", $db_user="user", $db_pass="password") {
        if(!$this->connection){
            try{
                $this->connection = new PDO($db_server, $db_user, $db_pass);
            } catch (PDOException $e) {
                $this->connection = null;
                die($e->getMessage());
            }
        }
        return $this->connection;
    }

}

$dbh = new db::connect();

$stmt = $dbh->prepare("SELECT * FROM questions where id = ?");
if($stmt->execute(array($_REQUEST['testid']))) {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
}
Odyssey answered 15/3, 2012 at 20:18 Comment(2)
the pseudo-variable $this is not available inside static methods and for static properties. You should use self::$property. Otherwise it will say property db::property not definedCrude
@BubuDaba son't edit improper code in the question as it can make other asnwers irrelevant. If you have a suggestion for the OP, then write an answer or a commentMarguerite
D
5

You could begin by not ever using Singleton pattern again. It (and static classes in general) is bad for all the same reasons why global variables in procedural programming are bad.

That said ... Instead of trying to enforce the uniqueness of the connection object, you should be just making sure that you using the same connection all over the place.

Here's an example of what i mean by that:

class Foo
{
    protected $connection = null;
    public function __construct( PDO $connection ) 
    {
        $this->connection = $connection;
    }
}

class Bar
{
    // all the same as in Foo
}

$connection = new PDO('sqlite::memory');

$foo = new Foo( $connection );
$bar = new Bar( $connection );

At this point both $foo and $bar objects will have access to the same PDO instance. If you have an object that needs access to database, then you just provide it with a connection in the constructor.

There are two videos you might want to watch (slides will contain Java code, but you should have no troble understanding it):

Diane answered 18/3, 2012 at 2:7 Comment(3)
Why do you say static classes are bad in general - I use a static class for my own PDO wrapper... Seems to work well for me. Is there a particular reason we should be avoiding them?Reprimand
@BenGriffiths , several reasons. The main problem is that with static classes you cannot use polymorphism. The execution of methods is tied to the name of the class. Also this is not really OOP. The static class is actually there only for a show. What you have are list of functions, bound in a namespace-ish structure. Anyway, you should just research the subject. There are a lot of materials. You can start here if you are willing to learn some better practices.Forrer
thanks, I'll look into it. My personal reason for using static is because I don't have to declare the class all over the place, or keep having to pass it to other objects - It's useful as a sort of constant object. I don't need a huge class in my own case, but having it wrapped up in a small static class makes it tidier and easier to manage.Reprimand
B
1

Persistent connections are built in:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

See Example #4 Persistent connections

Bradleigh answered 15/3, 2012 at 20:21 Comment(1)
This is useful even while it does not provide answer to original question, maybe it should be posted as comment... /*Or maybe because your*/ class Answer extends LogicException{}; try{ $to= include('some/more.php');''and $re=new Answer();if('you want'==$to);} catch(Points $for) {new Answer() or die($for.'this');}Correspondence

© 2022 - 2024 — McMap. All rights reserved.