Search code examples
phplaravellaravel-5tinker

Laravel Tinker creating new object that have constructer as an interface


I am trying to use Laravel Tinker to create a new object that have a constructer as an interface. MyClass.php

class MyClass{
 public function __construct(ApiInterface $APIloader)
    {
        $this->APIloader = $APIloader;
    }
}

ApiInterface.php

interface ApiInterface {
    ..
    ..
}

I wanted to test my classes in tinker so what i have done is that:

  1. php artisan tinker
  2. >> $a = new App\MyClass(new App\ApiInterface);

The error that i got is :

PHP Fatal error: Class 'App\ApiInterface' not found in eval()'d code on line 1

The tinker is not allow me todo that i feel like the tinker does not recognize an interface as a class

Any idea ?

Thanks


Solution

  • You cannot create an instance of an interface.

    If you want to test your code make a dummy class and use that.

    class TestApi implements ApiInterface {}
    
    $a = new App\MyClass(new App\TestApi);
    

    http://php.net/manual/en/language.oop5.interfaces.php

    A better alternative than a dummy class is just to use mock objects. They accomplish the same thing procedurally.

    https://laravel.com/docs/5.5/mocking

    https://phpunit.de/manual/current/en/test-doubles.html