In this post, we’ll explore how to create interface in Laravel 11 framework.
An interface in programming like a contract. It defines a set of methods that any implementing class must include. It is method to ensure consistency in behavior across different classes.
Laravel 11 present several updates, including a more application structure, rate-limiting and built-in check. Laravel 11 adds a new artisan command for creating interfaces.
To create a new interface, simply use the following command:
php artisan make:interface {interfaceName}
Example: Creating and Using interface
Let’s example to show this feature.
- Create the interface: We’ll create an interface name TestInterface with two methods: index() and listData().
- Implement the interface: We will create one classes, testingService, which implement the testInterface.
Create interface in Laravel Example:
First, you need to run following command to create “TestInterface” interface. Let’s run command.
php artisan make:interface Interfaces/TestInterface
Next, we will define the index() and listData() functions in the TestInterface.php file.
app/Interfaces/TestInterface.php
<?php
namespace App\interfaces;
interface TestInterface
{
public function index();
public function listDate($id);
}
Next, we will create one new service and implement “TestInterface” them. Run the following command.
php artisan make:class Services/testingService
Now, simply update the following code.
app\Services\TestingService
<?php
namespace App\Services;
use App\interfaces\TestInterface;
class TestingService implements TestInterface
{
/**
* Create a new class instance.
*/
public function index()
{
info("This is first page");
}
public function listData($id)
{
info("This data list page");
}
}
Next, we will create one controller with listDataValue method.
So, let’s run following command.
php artisan make:controller DemoController
app/Http/Controllers/DemoController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Services\TestingService;
use Illuminate\Http\Request;
class DemoController extends Controller
{
protected $testingService;
public function __construct(TestingService $testingService)
{
$this->testingService = $testingService;
}
public function listDataValue(Request $request)
{
$this->testingService->index();
return response()->json(['message' => 'Data getting successfully!']);
}
public function getDate($id)
{
$this->testingService->listData(1);
return response()->json(['message' => 'Data fetch successfully!']);
}
}
Now, we will create route to call controller methods. So, let’s add them.
<?php
use App\Http\Controllers\DemoController;
use Illuminate\Support\Facades\Route;
Route::get('list-data-value', [DemoController::class, 'listDataValue']);
Route::get('getData/{id}', [DemoController::class, 'getData']);
You can add more interfaces and use them.
I hope this tutorial help you.