Skip to content

Instantly share code, notes, and snippets.

@clzola
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clzola/77083c2cf9aaa02a370c to your computer and use it in GitHub Desktop.
Save clzola/77083c2cf9aaa02a370c to your computer and use it in GitHub Desktop.
<?php
include 'medoo.php';
class ActiveModel {
public static $table_columns = array();
public function __construct( $parameters = null ) {
$class_name = get_class($this);
$table_name = strtolower($class_name) . 's';
if( $parameters == null ) {
if( count(self::$table_columns) == 0 ) {
$database = new medoo();
$records = $database->query('SHOW COLUMNS FROM ' . $table_name)->fetchAll();
foreach ($records as $column_info) {
$this->$column_info['Field'] = null;
self::$table_columns[] = $column_info['Field'];
}
} else {
foreach (self::$table_columns as $column_name) {
$this->$column_name = null;
}
}
} else {
foreach ($parameters as $key => $value) {
$this->$key = $value;
}
}
}
public static function find( $ids ) {
$class_name = get_called_class();
$table_name = strtolower($class_name) . 's';
$database = new medoo();
$records = $database->select( $table_name, "*", [ 'id[=]' => $ids ] );
$objs = [];
foreach ($records as $record) {
$o = new $class_name();
foreach ($record as $key => $value)
$o->$key = $value;
if( $o->belongs_to !== null ) {
$belongsRecord = $database->select( $o->belongs_to . 's', "*", [ 'id[=]' => $o->{$o->belongs_to . '_id'} ]);
$belongs_to_class = ucfirst( $o->belongs_to );
$o->{$o->belongs_to} = new $belongs_to_class($belongsRecord[0]);
}
if( $o->has_many !== null ) {
$hasManyRecord = $database->select( $o->has_many, "*", [ strtolower($class_name) . '_id[=]' => $o->id] );
$hasManyClass = substr(ucfirst($o->has_many), 0, -1);
$o->{$o->has_many} = array();
foreach ($hasManyRecord as $record)
$o->{$o->has_many}[] = new $hasManyClass($record);
}
$objs[] = $o;
}
return $objs;
}
public function __get($name) {
if ( isset( $this->$name ) )
return $this->$name;
return null;
}
}
/*
Tables in DB
Table `users`
id => primary_key int(11) unsigned A_I
name => varchar(45)
pwd => varchar(45)
Table `posts`
id => primary_key int(11) unsigned A_I
body => varchar(45)
user_id => index int(11) unsigned constraints{ondelete: cascade, onupdate: noaction}
*/
class Post extends ActiveModel {
public $belongs_to = 'user';
}
class User extends ActiveModel {
public $has_many = 'posts';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment