Skip to content

Instantly share code, notes, and snippets.

@JBreit
Created April 29, 2014 01:45
Show Gist options
  • Save JBreit/11388897 to your computer and use it in GitHub Desktop.
Save JBreit/11388897 to your computer and use it in GitHub Desktop.
<?php
class Lesson extends Eloquent {
protected $fillable = ['title', 'body'];
}
<?php
class LessonsController extends \BaseController {
/**
* @var Acme\Transformers\LessonTransformer
*/
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$lessons = Lesson::all();
return Response::json([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
], 200);
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return Response
*/
public function show($id)
{
$lesson = Lesson::find($id);
if ( ! $lesson)
{
return Response::json([
'error' => [
'message' => 'Lesson does not exist'
]
], 404);
}
return Response::json([
'data' => $this->lessonTransformer->transform($lesson)
], 200);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return Response
*/
public function destroy($id)
{
//
}
}
<?php namespace Acme\Transformers;
class LessonTransformer extends Transformer {
public function transform($lesson)
{
return [
'title' => $lesson['title'],
'body' => $lesson['body'],
'active' => (boolean) $lesson['some_bool']
];
}
}
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::group(['prefix' => 'api/v1'], function()
{
Route::resource('lessons', 'LessonsController');
});
<?php namespace Acme\Transformers;
abstract class Transformer {
/**
* Transform a collection of lessons
*
* @param $items
* @return array
*/
public function transformCollection(array $items)
{
return array_map([$this, 'transform'], $items);
}
public abstract function transform($item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment