I’m trying to build a tiny ORM class that models will extend so, if for example I call the method User::find(1) it will give me the ‘User’ model that haves the id of 1 in the database.
This is my attempt:
class ORM
{
private static $table, $database;
function __construct() {
self::getConnection();
}
private static function getConnection (){
require_once('Database.php');
error_log('Getting connection');
self::$database = Database::getConnection(DB_PROVIDER, DB_HOST, DB_USER, DB_PASSWORD, DB_DB);
}
public static function find($id) {
$obj = null;
self::getConnection();
$query = "SELECT * FROM ? WHERE id = ?";
$results = self::$database->execute($query,null,array(self::$table,$id));
print_r();
if ($results){
$obj = new self($results);
}
return $obj;
}
}
And then, the class User for example.
include('ORM.php');
include('../../config.php');
class User extends ORM
{
public $id, $name;
private static $table = 'user';
public function __construct($data){
parent::__construct();
if ($data && sizeof($data)) { $this->populateFromRow($data); }
}
public function populateFromRow($data){
$this->id = isset($data['id']) ? intval($data['id']) : null;
$this->name = isset($data['name']) ? $data['name'] : null;
}
}
print_r(User::find(1));
I put those includes and that print_r just for testing, it won’t remain there after.
The issue is that it seems that the method find doesn’t read the $table from the class and it doesn’t read nothing. So the query isn’t executed fine and returns nothing but an error.
What am I doing wrong?
Change
selfin your code tostatic. Note that it will only work in php >= 5.3. Read more about late static binding