Skip to content

Instantly share code, notes, and snippets.

@natefanaro
Last active December 13, 2015 23:39
Show Gist options
  • Save natefanaro/4993164 to your computer and use it in GitHub Desktop.
Save natefanaro/4993164 to your computer and use it in GitHub Desktop.
I accidentally a simple ORM for php
<?php
class Model {
public $limit;
public $order_by;
public $query_properties = array();
public function __call($name, $arguments)
{
if (property_exists(__CLASS__, $name)) {
$this->$name = $arguments[0];
}
else {
$this->query_properties[$name] = $arguments[0];
}
return $this;
}
public function execute()
{
$model_name = get_class($this);
$table_name = preg_replace('/model\_/', '', strtolower($model_name));
$sql = 'SELECT * FROM ' . $table_name;
$params = array();
if ($this->query_properties) {
$sql .= ' WHERE ';
foreach ($this->query_properties as $field => $value) {
$params[$field] = $value;
$sql .= $field . ' = :' . $field . ' ';
}
}
if ($this->order_by) {
$sql .= 'ORDER BY ' . $this->order_by . ' ';
}
if ($this->limit) {
$sql .= 'LIMIT ' . $this->limit;
}
$stmt = pdo()->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, $model_name);
$stmt->execute($params);
if ($this->limit === 1) {
return $stmt->fetch();
}
return $stmt->fetchAll();
}
}
<?php
/*
Sample model class to use
the sql table for this sample:
CREATE TABLE `round` (
`round_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`account_id` int(11) unsigned NOT NULL,
`question_id` int(11) unsigned NOT NULL,
`date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`round_id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
*/
class Model_Round extends Model {
public $round_id;
public $account_id;
public $question_id;
public $date_time;
}
@natefanaro
Copy link
Author

You might be able to call this an ORM. You might even be able to get this code to compile. I was looking for an ORM to use in a new project. Turns out that is as easy as finding a decent framework for PHP. (Too many, steep learning curve, lots of setup, etc) I didn't find any. I started playing with PDO, and then its FETCH_CLASS fetch mode, and then classes, and then needed a quick way to query based off of id, and then I ended up with this.

This isn't complete of course. You can't do 'IS NOT null' queries, grouping, joins, etc. I might turn this in to a new repo some day where people can build from it. It may not work for you but it works for me.

Here is an example of how it is used:

$model = new Model_Round();
$round = $model->account_id($account_id)
            ->order_by('date_time DESC')
            ->limit(1)
            ->execute();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment