jumps4fun
jumps4fun

Reputation: 4132

How can I correctly use/import an interface in a php class?

I can't make interfaces work in my php/laravel project. I have a series of Controllers, which I want to implement an interface. And PhpStorm seems happy with my syntax. But I get a runtime error that the interface is not found, when I make a check if the current object indeed has the interface:

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use iTeamEntryController;

class TeamController extends Controller implements iTeamEntryController {...}

and then the Interface:

<?php
use Illuminate\Http\Request;
interface iTeamEntryController
{
    public function saveTeam(Request $request);
}

Here I get an error on the line defining the class, saying that interface 'iTeamEntryController' is not found. Both the class and the interface exists in the same folder.

I've been trying to find an example online, but everyone either has both the interface and the class declaration in the same file, or uses 'include_once' or 'require_once', which to me seems to be referring to files, and not OOP. So what am I doing wrong here? Why can't my interface be found?

Upvotes: 1

Views: 1682

Answers (1)

Robo Robok
Robo Robok

Reputation: 22703

Remember that the use clause wants you to specify an absolute class/interface/trait name, not relative to your current namespace.

The below is wrong, unless your controller is in a global namespace (which I'm sure isn't the case):

use iTeamEntryController; // wrong

And this - below - is correct:

use App\Http\Controllers\iTeamEntryController;

If you keep your interface in app/Http/Controllers directory, don't forget to specify a namespace:

namespace App\Http\Controllers;

If you want, on the other hand, your interface to be in a root directory, make sure it is there. Then, the namespace is not needed and your use clause is correct. Except, I'm pretty sure you don't want your interfaces in the root directory of your Laravel app.

Upvotes: 4

Related Questions