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.
Service container trong Laravel chính là công cụ hữu ích để quản lý các class dependency và depedency injection.
Binding dùng để đăng ký một class hay interface trong service container.
- Binding simple (truyền tên class hoặc interface muốn đăng ký cùng với một Closure trả về lớp được khởi tạo)
- Binding singleton (khai báo với Laravel rằng khi khởi tạo class này thì chỉ một lần duy nhất, những yêu cầu khởi tạo kế tiếp trong cùng một request chỉ trả lại object đã tạo lần đầu)
- Binding instance (giống singleton nhưng object khởi tạo đầu tiên không phải ở trong Closure mà là ở ngoài, nằm ở trước bind
- Binding primitives (tự động inject các dependency vào trong class)
// 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...)
Thanks for reading!