Laravel Service Container and Binding

Understanding dependency injection, service container, and binding types in Laravel.

Tue Jun 20 2023
— words · — minutes

Overview

Understanding dependency injection, service container, and binding types in Laravel.

Originally published on Jang Keyte's Blog.

This article covers Laravel Service Container and Binding — practical notes from real-world web development experience.

Code Examples

// Binding bình thường nhận tham số là Closure
$this->app->bind('MyUser', function($app) {
    return new \App\Models\User;
});

// Binding duy nhất 1 lần nhận tham số là Closure
$this->app->singleton('MyUser', function($app) {
    return new \App\Models\User;
});

// Binding duy nhất 1 lần nhưng nhận tham số là object
$user = new \App\Models\User; // Khởi tạo object lần đầu
$this->app->instance('MyUser', $user);

// Binding tự động injection
$this->app->when('App\Models\User') // chứa tham số namespace class nhận dependency, có thể nhận mảng.
    ->needs('$id') // chứa tên biến hoặc class
    ->give(1); // chứa giá trị của needs, có thể là Closure (trong trường hợp muốn gán giá trị là một object class...)

Read More

For the full Vietnamese version, switch language using the VI | EN toggle above, or visit the original post.


Thanks for reading!

Laravel Service Container and Binding

Tue Jun 20 2023
— words · — minutes