1

Here is my index.php

<?
require("Annonce.php");
$annonce = new Annonce();
$annonce->id=1;
$annonce->delete();

?>

My Annonce.php is!

<?php 

require("DB.php");
class Annonce extends DB {
}    
 ?>

and finally DB is:

<?php 
$db = new PDO('mysql:host=localhost;dbname=annonces;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


class DB {
    public static $debug = true;    
    function __construct() {
        # code...
    }
    function delete() {
        $id = $this->id;
        $table = get_class($this);
        $sql="delete from $table where id=$id";     
        if ($this::$debug) echo $sql;

    }

    function get() {
        $sql="select *...";
    }

}
 ?>

I don't know what is the best strategy to define the $db connection ?

If I define it inside DB class, it will make a connection any time an "Annonce" object is created. Maybe using $db as GLOBAL (which I think is not clean)

Any suggestion for that ?

yarek
  • 11,278
  • 30
  • 120
  • 219

2 Answers2

1

Create a Singleton ,some thing like this:

class DB
{
   private $_db;
   private $_instance;
   private function __construct() 
   {

    $this->_db = $db = new PDO('mysql:host=localhost;dbname=annonces;charset=utf8', 'root', '');

}

public static function getInstance()
{
    if(!(self::$_instance instanceof DataBase)){
      $c = __CLASS__;
      self::$_instance = new $c;
    }
    return self::$_instance;
}
//.....other code

}

use it by :

$db = DB::getInstance();
Raymond Cheng
  • 2,425
  • 21
  • 34
0

You could define your connection as a service and use a Dependency Injuection Container (DIC) to provide the connection for any other feature/module/class needing it by providing the Dependency Injection Container. Pimple is a simple DIC Solution by "the people who brought us Symfony".

Having a DIC is a good idea anyway.

THis might seem "over the top" for your problem (since a Singleton would definetly solve your problem) but considering a DIC will improve your work a lot more. And you asked for a clean Solution. The Singleton Design Pattern is only clean if you do not use Unit Tests since Singletons will get you into trouble with mocking.

Read more about it here.

Community
  • 1
  • 1
Andresch Serj
  • 35,217
  • 15
  • 59
  • 101