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 ?

2
  • Maybe you will be interested by the Singleton pattern. Commented Mar 14, 2014 at 10:03
  • Or the Dependency Injection Container Pattern Commented Mar 14, 2014 at 10:05

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.