user3682707
user3682707

Reputation: 267

Laravel Why I can access the method was not declared from Interface?

I have a problem like below:

I have an Interface name IBannerService

<?php
namespace App\Interfaces;

interface IBannerService
{
public function add($data);
public function list();
public function get($data);
public function delete($data);
}

and an instance name BannerService

class BannerService implements IBannerService
{

public function add($data)
{
    return true;
}

public function list()
{
    return true;
}

public function get($data)
{
    return true;
}

public function delete($data)
{
    return true;
}

public function test()
{
    print_r("aaaa");
    die();
}
}

finally I have a Controller name HomeController

class HomeController extends Controller
{
   public function __construct(
    IBannerService $bannerService
    )
   {
     $this->bannerService = $bannerService;
   }
   public function index()
   {
    $listBanner = $this->bannerService->list();
    $this->bannerService->test();
   }

}

My configuration:

class DIServiceProvider extends ServiceProvider
{
    $this->app->bind(
        'App\Interfaces\IBannerService',
        'App\Services\BannerService'
    );
}

In app.php:

'providers'=>[
    App\Providers\DIServiceProvider::class,
]

The code run well with $listBanner = true (just for testing).

The problem is:

Test Method was not declared in interface IBannerService but still go through and print out "aaa" the die.

Did I do something wrong?

Please suggest me, thank you!

Upvotes: 0

Views: 640

Answers (1)

Jerodev
Jerodev

Reputation: 33186

That's perfectly normal functionality.

In the Laravel container you defined that when you ask for a IBannerService object, you want to get a BannerService class. And that is what you got. BannerService is an implementation of IBannerService, so no problem for the typehint.

A class is not limited to the functions defined by its interface so you can add as many other functions as you like. I wouldn't recommend it though, things like smart IDE's and phpstan would give you errors or warnings because to them, the variable is an implementation of IBannerService and this does not have a test() function.

If you really want to use more functions I would even recommend to use BannerService as the typehint. This way, static code analysis will still work.

Upvotes: 2

Related Questions