[Laravel] Extraction

1. ex: make a file app/Acme/Transformers/Transformer.php

<?php namespace Acme\Transformers;
    
abstract class Transformer{
    public function transformCollection(array $items)
    {
        return array_map([$this, 'transform'], $items);
    }
    
    public abstract function transform($item);
}

2. ex: make a file app/Acme/Transformers/LessonTransformer.php

 $lesson['title'],
            'body' => $lesson['body'],
            'active' => (boolean) $lesson['some_bool']
        ];
    }
}

3. update composer.json: add app/Acme to classmap

"autoload": {
		"classmap": [
			"app/commands",
			"app/controllers",
			"app/models",
			"app/database/migrations",
			"app/database/seeds",
			"app/tests/TestCase.php",
			
			"app/Acme"
		]
	},

4. update app/controllers/LessonsController.php

<?php
use Acme\Transformers\LessonTransformer;

class LessonsController extends \BaseController {
    
    /**
     * @var My\Transformers\LessonTransformer
     */
    protected $lessonTransformer;
    
    function __construct(LessonTransformer $lessonTransformer)
    {
        $this->lessonTransformer = $lessonTransformer;
    }

public function index()
  {
    // 1. All is bad
    // 2. No way to attach meta data
    // 3. Linking db structure to the API output
    // 4. No way to signal headers/response codes
    
    //return Lesson::all();
  
    $lessons = Lesson::all();
    //return Response::json([
      //'data' => $lessons->toArray()
    //], 200);
    //return Response::json([
      //'data' => $this->transformCollection($lessons)
    //], 200);
    return Response::json([
      'data' => $this->lessonTransformer->transformCollection($lessons->all())
    ], 200);
  }

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)
        //'data' => $this->transform($lesson->toArray())
    ], 200);
  }

}