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!!