Skip to content

Instantly share code, notes, and snippets.

@noherczeg
Last active December 30, 2015 12:59
Show Gist options
  • Save noherczeg/7832637 to your computer and use it in GitHub Desktop.
Save noherczeg/7832637 to your computer and use it in GitHub Desktop.
Laravel dynamic relation loader
<?php
// rutes.php
Route::get('/users/{userId}/events/{eventId}', function()
{
return Response::json(entityLoader('MyApp\Core\User\User'));
});
Route::get('/users/{userId}/events', function()
{
return Response::json(entityLoader('MyApp\Core\User\User'));
});
Route::get('/events', function()
{
return Response::json(entityLoader('MyApp\Core\Event\Event'));
});
Route::get('/events/{eventId}', function()
{
return Response::json(entityLoader('MyApp\Core\Event\Event'));
});
/*
|
| Dynamically loads a base entity, or any of it's relations from the URI :)
|
| If ?page is set, it sends the Paginator object
| If ?limit is set, it sets the limit
| If ?sort is set it sets the sorting as well
|
| When the URI ends with an ID and ?with=all is set, it calls the Model's
| 'which is last in the Query String) attachDown() method which should look
| like this:
|
| public function attachDown()
| {
| return $this->load('eventType', 'etc');
| }
|
*/
function entityLoader($baseEntity)
{
$pagingSize = 1;
$splits = preg_split('/\//', Route::getCurrentRoute()->getPath(), -1, PREG_SPLIT_NO_EMPTY);
// we remove the first param since we provide the namespaced class Name for the function
array_shift($splits);
$currentRoute = Route::getCurrentRoute();
$routeParams = $currentRoute->getParameters();
function isParam($asd)
{
if (strpos($asd, '{') !== FALSE)
return true;
return false;
}
// Instantiation of our base Entity. This will be used to start off the chaining.
$entity = new $baseEntity;
$runs = count($splits);
foreach ($splits as $split) {
// if are iterating on a param, we should select an Entity
if (isParam($split)) {
$id = array_shift($routeParams);
$entity = $entity->find($id);
if ($runs == 1 && Input::get('with') === 'all') {
$entity->attachDown();
}
// otherwise we load the relation, and get it as well
} else {
$entity = $entity->load($split)->getRelation($split);
// if the current param is the last in the URI and the page param is set, we create a Paginator
if ($runs == 1 && Input::get('page')) {
// if the limit param is set, we override our default setting
if (Input::get('limit')) {
$pagingSize = Input::get('limit');
}
$paginator = Paginator::make($entity->toArray(), count($entity), $pagingSize);
// if the sort param is set, we se the sorting as well
if (Input::get('sort')) {
$paginator->appends(array('sort' => Input::get('sort')))->links();
}
$entity = $paginator;
}
}
$runs--;
}
return $entity;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment