I'm trying to build a small, seemingly simple app in pure php (can't use any framework or fancy tools such as orms).
I got started by defining object representing my models. My idea is to have a Model
base class, which would hold a static pdo instance to access the database, and two "concrete" model classes inheriting from it and implementing the custom method they'll need.
Well, boy am i rusty in PHP. It's also the first time i'm doing actual oop with it (i've done enough of it in other languages (C# and python, mainly) to understand how it's supposed to work, but some subtleties might very well elude me.
If anyone cares to help, here's what i have so far:
<?php
/**
* Base model class, handling basic db connection
*/
Class Model {
protected static $db;
public static function initDb() {
self::$db = new PDO(DB_CONNECTION_STRING, DB_USER, DB_PSWD);
}
protected function _prepare_request($sqlstmnt) {
return self::$db->prepare($sqlstmnt);
}
}
Model::initDb();
/**
* Model class for Category objects
**/
Class Categorie extends Model {
private $request_getSingle = NULL;
public function __contruct() {
$this->request_getSingle = $this->_prepare_request(
"SELECT * FROM categorie WHERE cat_id = :id;"
);
}
public function getById($id) {
$poop = $this->request_getSingle->execute(array(':id' => $id));
$res = $poop->fecthAll();
print_r($res);
}
}
// Debug tests:
$c = new Categorie();
var_dump($c);
$c->getById('1');
print_r($c);
echo 'done';
?>
Seems like my query objects are not initialized properly - Here's what i get when i run that silly debug code:
object(Categorie)#3 (1) { ["request_getSingle":"Categorie":private]=> NULL }
Fatal error: Call to a member function execute() on a non-object in /home/raphi/dev/naoned-test/models/categories.php on line 18
Call Stack:
0.0003 648192 1. {main}() /home/raphi/dev/naoned-test/models/categories.php:0
0.0011 661784 2. Categorie->getById() /home/raphi/dev/naoned-test/models/categories.php:27
I have NO idea what exactly is going wrong. I might be using static variables wrong, or miss something about how PDO works.
Hope that's clear enough, and thank to anyone willing to help (there might be somme silly errors here and there caused by helpless hacking around).
EDIT:
After hacking around, turns out that if i call the PDO prepare, execute, etc... methods within getById
, everything works fine. But why can't i keep the prepared SQL statement as an instance variable ? Having to call prepare
each time i want to access it seems to defeat its purpose...
EDIT:
Well... This seems fixed, but i still don't understand.
I've replaced my request_getSingle
variable by an array, which contains several prepared statements (which is what i planned to do eventually anyway...) and everything works fine.
I don't get it. If i store them in an array, they can be accessed from the class's other methods, but if i store them as regular attributes, they can't ?
If anyone has some idea of what's going on, i'm still interested...