pdo connection position in php class -


i'm using pdo , have number of classes. every time use class, don't use database-related functions. keep using class until @ end might work database, save object db.

so i'm doing this:

class {    protected $pdo;       function connect()      {         $this->pdo = new pdo( "mysql:host=".zconfig::read('hostname').";dbname=".zconfig::read('database'), zconfig::read('username'), zconfig::read('password'));         $this->pdo->setattribute(pdo::attr_errmode, pdo::errmode_exception);      }       /* lots of functions doing lots of non-db things */       function savetodb()      {    $this->connect();           $this->pdo->prepare("some sql saves stuff");           // db-related pdo work      }  } 

my question - reasonable? way lot of code?

as see it, there 3 options:

  1. the way i'm doing - connecting database in functions database related. these means each time run db-related function.
  2. open connection in constructor, in case open once, end opening when don't need it, feel i'll creating connections nothing.
  3. on other hand, use singleton database class this:

    pdo connections - max connections

i have 3 related objects on page, , , don't need connect db more once on page. design safer?

you should use di, in class instantiate connection, when object defined ex:

class foo{     public $conn;      function __construct($conn){     $this->conn = $conn;     }      function dosomething(){     } } 

now, if find yourself, not wanting instanciate connection, whenever on page/work not need database connection, , slows page, while trying connect, use pdo attribute

att_persistent property like:

$conn = new pdo('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx',                  array( pdo::attr_persistent => true )         );  $object = new foo($conn); 

simply, once, open page, , connection establish attr_persistent method store connection, pretty sessions work, , keep feeding page, , helping creating new connection db, every time refresh page, or go on page. try, it.. , you'll see how faster pages load.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -