Search code examples
phplaravelooplaravel-5.3

How to implement Abstract class in laravel 5.3


I was following Laracasts Api course and at a point i'm getting this error

Whoops, looks like something went wrong.
ReflectionException in Container.php line 809:
Class App\Acme\Transformers\LessonTransformer does not exist

i created a abstract class in app\Acme\Transformers\Transformer.php

<?php

namespace App\Acme\Transformers;

abstract class Transformer {

    //transformCollection the lessons data and return only requried fields
    public function transformCollection($items) {

        return array_map([$this, 'transform'], $items);

    }


    //transform the lessons data and return only requried fields of perticular id
    public abstract function transform($item);

}

and app\Acme\Transformers\LessonTransformer.php

<? php 

namespace App\Acme\Transformers;

class LessonTransformer extends Transformer {

    public function transform($lesson) {

        return [
            'title'  => $lesson['title'],
            'body'   => $lesson['body'],
            'active' => (boolean) $lesson['completed']
        ];

    }

}

And My controller is LessonsController.php

<?php

namespace App\Http\Controllers;

use App\lesson;
use Response;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;

class LessonsController extends Controller {

    protected $lessonTransformer;

    function __construct(LessonTransformer $lessonTransformer) {

        $this->lessonTransformer = $lessonTransformer;

    }

    //fetch all and pass a metadata 'data' 
    public function index() {

        $lessons = Lesson::all();

        return Response::json([

            'data' => $this->lessonTransformer->transform($lessons)

        ], 200);
    }


    //fetch by id
    public function show($id) {

        $lesson = Lesson::find($id);

        if(! $lesson) {

            return Response::json([
                'error' => [
                    'message' => 'No Response Please Try Again'
                ]
            ], 404);
        }

        return Response::json([

            'data' => $this->lessonTransformer->transform($lesson)

        ], 200);
    }

}

I don't know what i'm missing looking forward for much needed help

Thank You


Solution

  • As we can see by the error message, the problem is not related to the Abstract class Transformer, it was not able to reach that class yet because it was not able to find the LessonTransformer class?

    Class App\Acme\Transformers\LessonTransformer does not exist
    

    Looking at your classes looks like all namespaces are good and, if you are using PSR4, there's no need to execute composer dumpautoload, it find it automatically.

    But your class is not found and usually this happens because:

    1) The file is misplaced (is it in the correct dir?).

    2) The file is not correctly named.

    3) You have an error in the file and PHP was not able to understand it as a class.