Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- require_once(dirname( __FILE__ ).'/../vendor/phpDataMapper/Model.php');
- require_once(dirname( __FILE__ ).'/../vendor/phpDataMapper/Database/Adapter/Mysql.php');
- require_once(dirname( __FILE__ ).'/../vendor/spyc.php');
- $__database_yaml__ = dirname(__FILE__).'/../config/database.yaml';
- /*
- *database.yaml format
- *
- *db:
- * {env}:
- * host: {host}
- * port: {port}
- * database: {database}
- * user: {user}
- * password: {password}
- *schema:
- * {class_name}: <- called 'Mapper class' in PHP DataMapper
- * table: {table_name}
- * fields:
- * {field_name}:
- * {attr}: {value} <- if {type} not defined
- * relations:
- * {relation_name}: <- when HasMany, pluralize e.g) post -> posts
- * relation: {relation_type} <- 'HasOne' or 'HasMany'
- * mapper: {mapper_class}
- * foreign_keys:
- * {my_pkey}: {foreign_key}
- */
- class Model extends phpDataMapper_Model {
- public static function datetime_now(){
- return date('Y/m/d H:i:s', strtotime('now'));
- }
- public static function _make($attributes, $adapter=null, $klass){
- if(is_null($adapter)) $adapter = DB::proxy();
- $model = new $klass($adapter);
- if(is_null($attributes)) return $model->get();
- $pkey_name = $model->getPrimaryKeyField();
- $is_update = array_key_exists($pkey_name, $attributes);
- $model_row = $is_update?$model->get($attributes[$pkey_name]):$model->get();
- $related = array();
- foreach($attributes as $attr => $value){
- if(array_key_exists($attr, $model->fields)){
- $model_row->{$attr} = $value;
- }elseif(is_array($value) && !is_null($model->relations[$attr])){
- $related[] = $attr;
- }
- }
- if(!$is_update && !array_key_exists('created_at', $attributes) && array_key_exists('created_at', $model->fields))
- $model_row->created_at = self::datetime_now();
- if(!array_key_exists('updated_at', $attributes) && array_key_exists('updated_at', $model->fields))
- $model_row->updated_at = self::datetime_now();
- $last_id = $is_update?$model->update($model_row):$model->insert($model_row);
- $saved = $model->get((int)$last_id);
- foreach($related as $rel){
- $rattributes = $attributes[$rel];
- $fkeys = array();
- foreach($model->relations[$rel]['foreign_keys'] as $pkey => $fkey){
- $fkeys[$fkey] = $saved->{$pkey};
- }
- $rklass = $model->relations[$rel]['mapper'];
- switch($model->relations[$rel]['relation']){
- case 'HasOne':
- self::_make(array_merge($rattributes, $fkeys), $adapter, $rklass);
- brake;
- case 'HasMany':
- foreach($rattributes as $rattr) self::_make(array_merge($rattr, $fkeys), $adapter, $rklass);
- brake;
- }
- }
- return $saved;
- }
- public static function _is($conditions, $orderby, $adapter=null, $klass){
- if(is_null($adapter)) $adapter = DB::proxy();
- $model = new $klass($adapter);
- return (!is_array($conditions)) ? $model->get($conditions) : $model->first($conditions, $orderby);
- }
- public static function _are($conditions, $orderby, $adapter=null, $klass){
- if(is_null($adapter)) $adapter = DB::proxy();
- $model = new $klass($adapter);
- return $model->all($conditions, $orderby);
- }
- }
- class DBConfigration{
- public static function generateCode($config){
- if(is_null($config)) trigger_error("no configuration for generate database-classes code. please check '{$__database_yaml__}'", E_USER_ERROR);
- $code .= '
- class DB {
- public static $env = "development";
- public static function proxy($env=null){
- if(!is_null($env) && is_callable("self::{$env}")) self::$env = $env;
- $env = self::$env;
- if(is_callable("self::{$env}")){
- return self::$env();
- }else{
- trigger_error("cannot find database definition of \'{$env}\'. please check database.yaml.", E_USER_ERROR);
- }
- }
- ';
- foreach($config['db'] as $db_name => $info){
- $code .= "
- public static function {$db_name}(){
- return new phpDataMapper_Database_Adapter_Mysql('{$info['host']}', '{$info['database']}', '{$info['user']}', '{$info['password']}');
- }
- ";
- }
- $code .= '
- }
- ';
- foreach($config['schema'] as $class => $schema){
- $code .= '
- class '.$class.' extends Model {
- public $table = "'.$schema['table'].'";
- public $fields =
- array(
- ';
- foreach($schema['fields'] as $key => $value){
- $attributes ='';
- if(!is_array($value)){
- $attributes = "'type' => '{$value}'";
- if ($key == 'id') $attributes .= ",'primary' => true";
- }else{
- foreach($value as $k => $v){
- $attributes .= ($v == 'true') ? "'{$k}' => true,": "'{$k}' => '{$v}',";
- }
- }
- if($key == 'timestamps'){
- $code .= "
- 'created_{$value}' => array('type' => 'datetime'),
- 'updated_{$value}' => array('type' => 'datetime'),
- ";
- }else{
- $code .= "
- '{$key}' => array({$attributes}),
- ";
- }
- }
- $code .= '
- );
- ';
- if($schema['relations']){
- $code .= '
- public $relations =
- array(
- ';
- foreach($schema['relations'] as $key => $value){
- foreach($value['foreign_keys'] as $k => $v){ $fkeys .= ($v == 'true') ? "'{$k}' => true," : "'{$k}' => '{$v}',"; }
- $code .= "
- '{$key}' =>
- array(
- 'relation' => '{$value['relation']}',
- 'mapper' => '{$value['mapper']}',
- 'foreign_keys' => array({$fkeys})
- ),
- ";
- }
- $code .= '
- );
- ';
- }
- $code .= '
- public static function make($attributes, $adapter=null){ return parent::_make($attributes, $adapter, get_class());}
- public static function is($conditions=array(), $orderby=array(), $adapter=null){ return parent::_is($conditions, $orderby, $adapter, get_class());}
- public static function are($conditions=array(), $orderby=array(), $adapter=null){ return parent::_are($conditions, $orderby, $adapter, get_class());}
- }
- ';
- }
- return $code;
- }
- }
- eval(DBConfigration::generateCode(Spyc::YAMLLoad($__database_yaml__)));
- ?>
Add Comment
Please, Sign In to add comment