Skip to content

Instantly share code, notes, and snippets.

@ubergeekzone
Created April 14, 2016 22:38
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 ubergeekzone/f4d1aca177f05f242993b56b4fee7fdb to your computer and use it in GitHub Desktop.
Save ubergeekzone/f4d1aca177f05f242993b56b4fee7fdb to your computer and use it in GitHub Desktop.
Eloquent Dynamic Modules w/ Relationship Support - eval() way
<?php
$model_confg = array(
"Models" =>
array(array('className'=> "Books", 'classTable'=>'books', "fillable" => "book_name"), array('className'=> "Authors", 'classTable'=>'authors', "fillable" => "")),
"Relations" =>
array("Authors" =>
array("books" =>
array("function" => function( $self ) {
return $self->belongsToMany('Books');
}
))));
function eloquent_dym_models($models)
{
$eval = "";
foreach ($models as $key => $value) {
$recordType = $value['className'];
$recordTable = $value['classTable'];
$f = $value["fillable"];
$eval .= "class $recordType extends Illuminate\Database\Eloquent\Model {
protected \$table = '$recordTable';
protected \$fillable = [$f];
public function __call(\$method, \$parameters) {
\$class_name = class_basename( \$this );
if(array_key_exists(\$class_name, \$parameters[0])) {
\$func = \$parameters[0][\$class_name][\$method]['function'];
return \$func(\$this);
}
return parent::__call(\$method, \$parameters);
}
}";
}
eval($eval);
}
eloquent_dym_models($model_confg['Models']);
$authors = Authors::find(1);
$data['authors'] = $authors->toJson();
$data['books'] = $authors->books($model_confg['Relations'])->get()->toJson();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment