Skip to content

Instantly share code, notes, and snippets.

@tommymarshall
Created April 5, 2016 14:29
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 tommymarshall/b38f543daa839e46c7d4466c1bc434ff to your computer and use it in GitHub Desktop.
Save tommymarshall/b38f543daa839e46c7d4466c1bc434ff to your computer and use it in GitHub Desktop.
create new instance from class names
<?php
class Feed {
public function items()
{
return $this->feedItems()->map(function($element) {
return $this->createInstance($element['content_type'], $element);
});
}
private function createInstance($content_type, $attributes)
{
$class_name = preg_replace('/\s+/', '', $content_type);
$namespaced_class_name = "\\App\\Models\\{$class_name}";
if (!class_exists($namespaced_class_name)) {
throw new \Exception("Class '{$namespaced_class_name}' not found");
}
return new $namespaced_class_name($attributes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment