use Illuminate\Support\ServiceProvider;
use App\ReportGeneratorInterface;
use App\MockReportGenerator;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
// ผูกอินเทอร์เฟซกับ Mock Implementation ใช้ในการทดสอบ
$this->app->bind(ReportGeneratorInterface::class, function ($app) {
return new MockReportGenerator();
});
}
}
// Controller ที่ใช้ dependency
class ReportController extends Controller
{
protected $reportGenerator;
// รับ ReportGeneratorInterface ผ่าน constructor
public function __construct(ReportGeneratorInterface $reportGenerator)
{
$this->reportGenerator = $reportGenerator;
}
public function generate()
{
return $this->reportGenerator->generateReport();
}
}
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\ReportGeneratorInterface;
use App\MockReportGenerator;
class ReportControllerTest extends TestCase
{
use RefreshDatabase;
public function test_generate_report()
{
$this->mock(ReportGeneratorInterface::class, function ($mock) {
$mock->shouldReceive('generateReport')->once()->andReturn('Mock Report');
});
$response = $this->get('/report');
$response->assertStatus(200);
$response->assertSee('Mock Report');
}
}
ความสามารถในการกำหนดค่าเอง (Binding)
ทาง Dev สามารถผูกอินเทอร์เฟซกับการทำงานเฉพาะเจาะจงหรือกำหนดไปยังการทำงานที่ต่างออกไปได้ เช่น
use App\Contracts\PaymentGatewayInterface;
use App\Services\StripePaymentGateway;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
// Binding the interface to a specific implementation
$this->app->bind(PaymentGatewayInterface::class, StripePaymentGateway::class);
}
}
use App\Services\UserService;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(UserService::class, function ($app) {
return new UserService($app->make(UserRepository::class));
});
}
}