Skip to content

Very Basic PHP ORM

by Iain on February 14th, 2010

Recently, I’ve needed to go back to PHP, and decided to forgo an full ORM engine instead to use PHP PDO functions, and a little class trickery.

I wanted something that’s easy to call, and allows me to setup the database, setup variables, and return an array -> object result.

PHP 5 introduced quite a bit of OOP methods, tricks, and functions. Although PHP still largely is a functional, procedural based programming language, its support for objects is getting slowly better.

Regarding the ORM, I decided to make two classes, (which could be expanded to more, I might end up with two in the final process). One contains a bunch of functions which build SQL queries from a $args array, and class variables. That way, the queries can be changed in one central place, and can be formulated with the database.

The other class, the database class, takes care of connecting to the database, calling the method within the other class to build the query, execute the query, and return the result as objects in an array.

Pretty simple– but it took some time to remember all the functions and work around the class structure, Ruby is so much nicer to manipulate classes. PHP lambdas are very poor.

Here is the code for the Database Controller:

class DBRunner {
    public $db = array('name'=>'dbname', 'user'=>null, 'password'=>null);
    public $dbdriver = null;
 
    public function __construct(){
        if (!$this->dbdriver){
            $this->connect($this->db);
        }
    }
 
    private function connect($db){
        try {
             $this->dbdriver = new PDO('mysql:host=localhost;dbname='.$db['name'],$db['user'], $db['password']);
        } catch(PDOException $e){
             echo('Error Connecting to DB: '+$e); //Please use for development ONLY. Handle properly in production.
        }
    }
 
    public function __destruct(){
        $this->dbdriver = null; //Closes the PDO Connection
    }
 
    public function __call($method_name, $args){
        if (method_exists(Model, $method_name)){ //If our method exists in the Model class
            foreach ($args as $arg){ //Simple Escaping
                if (is_string($arg)){
                    $args[$arg] = mysql_escape_string($arg);
                }
            }
            $model = new Model; //Make a new 'model' class
            $model->args = $args; //Set the args
            $sql_string = $model->$method_name(); //Call the method to get the query
            if ($this->statement = $this->dbdriver->query($sql_string)){
                $this->result = array(); //Build Results
                foreach($this->statement->fetch(PDO::FETCH_OBJ) as $object){
                    array_push($this->result, $object);
                }
                return $this->result; //Return Results
            } else {
                echo('Database Error - '); //Error Debugging - Development
                print_r($this->dbdriver->errorInfo());
            }
        } else {
            throw new Exception('Database Method Not Found');
        }
    }
}

And example code for the Model class:

class Model{
    public $args;
    function getAllPeople(){
         $ids = implode(',',$args['ids']);
         return "SELECT name, email, pic FROM people WHERE id IN ({$ids});"
    }
}
VN:F [1.4.8_745]
Rating: 10.0/10 (1 vote cast)

From → Uncategorized

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS