0

I have a Abstract class for my database Database.php:

abstract class Database {
private $host      = DB_HOST;
private $user      = DB_USER;
private $pass      = DB_PASS;
private $dbname    = DB_NAME;

private $dbh;
private $error;

private $stmt;

public function __construct(){        
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    // Set options
    $options = array(            
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION            
    );
    // Create a new PDO instanace
    try{
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}

public function query($query){        
    $this->stmt = $this->dbh->prepare($query);
    }
}

Then I have a Recipe class that extends Database with a static function:

class Recipe extends Database{

private $id;
private $slug;
private $title;     

public function __construct {
       $this->id=$id;
       $this->slug=$slug;
   $this->title=$title;
       parent::__construct();
    }

    public static function getAll () {      

   self::query('select * from recipes order by id');        
   $rows = self::resultset();       
   $recipes=array();
   foreach ($rows as $row){// show}
    }

Finally in my index.php:

$recipes=Recipe::getAll();

What's the correct way to do this?

I don't want to create a instance of Recipe each time I need to do a SQL query like this method:

$recipes=new Recipe();
$recipes->getAll();

then in recipes class:

$this->query('select * from recipes order by id');      
$rows = $this->resultset();

Thanks!!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
kurtko
  • 1,978
  • 4
  • 30
  • 47
  • You probably should not be extending your database class for your recipe class. Would you should likely do is have some concrete database class and pass an instance of it to the recipe class. After all, why does a recipe class need to have a database connection logic in its constructor, it just need access to a valid database object with which it can perform queries. – Mike Brant Apr 24 '14 at 16:21
  • 1
    recipes shouldn't be a child of the DB. It'd be better if your recipes constructor embedded an instance of the db class, e.g. `$this->db = new Database()`, then use `$recipeobject->db->query(...)`. – Marc B Apr 24 '14 at 16:25
  • See this [answer](http://stackoverflow.com/a/16605563/747609) – IROEGBU Apr 24 '14 at 16:31

0 Answers0