前回の続きからソースを記載し、個人的なメモとして残していく。
独自クラスTestRepositoryをIndexControllerで使えるようにする。
https://qiita.com/pig_buhi555/items/12ff451b45b78d6f94f6
1. ソース
TestServiceProviderを作成し、修正する。
php artisan make:provider TestServiceProvider
artisanコマンド実行後、App\Providers\TestServiceProvider::class,は自動で書き込まれる。
laravel12/bootstrap/providers.php
<?php
return [
App\Providers\AppServiceProvider::class,
App\Providers\TestServiceProvider::class,
];
laravel12/app/Providers/TestServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Http\Controllers\IndexController;
use App\Repositories\Repository;
use App\Repositories\TestRepository;
class TestServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register(): void
{
logger('register');
// whenはDI(依存性注入)を行うコントローラー
$this->app->when([
IndexController::class,
])
// needsでDIする抽象クラス・インターフェース
->needs(Repository::class)
// 具象クラス(インスタンス化できるクラス)
->give(fn() => new TestRepository());
}
/**
* Bootstrap services.
*/
public function boot(): void
{
//
logger('boot');
}
}
laravel12/app/Repositories/TestRepository.php
<?php
namespace App\Repositories;
class TestRepository implements Repository
{
public function test1()
{
logger('test1');
}
public function test2()
{
logger('test2');
}
public function test3()
{
logger('test3');
}
}
laravel12/app/Repositories/Repository.php
<?php
namespace App\Repositories;
interface Repository
{
public function test1();
public function test2();
public function test3();
}
laravel12/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\IndexController;
// Route::get('/', function () {
// return view('welcome');
// });
Route::get('/', [IndexController::class, 'index']);
IndexControllerを作成。
php artisan make:controller IndexController
laravel12/app/Http/Controllers/IndexController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\Repository;
class IndexController extends Controller
{
//
public function __construct(
// App\Repositories\TestRepositoryが使われる
protected Repository $repository,
)
{}
public function index()
{
$test1 = $this->repository->test1();
}
}
2. URLにアクセス
3 ログ
[2025-05-26 16:15:41] local.DEBUG: register
[2025-05-26 16:15:42] local.DEBUG: boot
[2025-05-26 16:15:42] local.DEBUG: CustomEmptyStringsToNull
[2025-05-26 16:15:42] local.DEBUG: AppendMiddleware
[2025-05-26 16:15:42] local.DEBUG: test1
4. 参考
ありがとうございました。
https://zenn.dev/kkatou/books/laravel-best-practices/viewer/setting-providers