I. Zero Configuration Resolution
II. Binding

  1. Basic Binding
    1.1 Simple Binding
    1.2 Binding a Singleton
    1.3 Binding Scoped Singletons
    1.4 Binding Instances
  2. Binding Interfaces to Implementations
  3. Contextual Binding
  4. Binding Primitives
  5. Binding Typed Variadics
    5.1 Variadic Tag Dependencies
  6. Tagging
  7. Extending Bindings

III. Resolving


Trong phần trước chúng ta đã tìm hiểu về Simple Binding, Binding a Singleton. Trong bài này chúng ta sẽ tìm hiểu tiếp về Binding Scoped Singletons và Binding Instances

1.3 Binding Scoped Singletons

Các bind như sau

use App\Services\Transistor;
use App\Services\PodcastParser;
use Illuminate\Contracts\Foundation\Application;
 
$this->app->scoped(Transistor::class, function (Application $app) {
    return new Transistor($app->make(PodcastParser::class));
});

Scoped tương tự như Singleton. Tuy nhiên, object instance sẽ được làm mới sau mỗi lifecycle. Hiểu đơn giản là khi một request (hoặc một job) đang được xử lý thì object instance sẽ là giống nhau. Nhưng khi request/job đó kết thục, bắt đầu một lifecycle mới thì object instance sẽ được constructed lại.

1.4 Binding Instances

Cách dùng

use App\Services\Transistor;
use App\Services\PodcastParser;

// Đây là một instance "có sẵn"
$service = new Transistor(new PodcastParser);
// Và bạn muốn bind nó vào Container
$this->app->instance(Transistor::class, $service);

Bạn dùng instance khi bạn có một object instance có sẵn, và bạn muốn bind nó vào Container
Ví dụ tiếp theo

/*
* Ví dụ này lấy từ nguồn: https://viblo.asia/p/laravel-beauty-tim-hieu-ve-service-container-3KbvZ1wLGmWB
*/

// $now là một instance có sẵn
$now = time();
// bind nó vào trong Container
app()->instance('now', $now);
// Như vậy instance "có sẵn" sẽ giống như instance resolve từ Container
$now === app('now'); // true

Binding Instance tương tự như Binding Singleton ở điểm instance chỉ được tạo ra một lần duy nhất, và sẽ giữ lại trong suốt quá trình sử dụng (giống nhau ở mọi thời điểm resolve binding)

Như vậy chúng ta đã đi qua 4 khái nệm về Basic binding.

Chúng ta nghỉ tay ở đây và cùng suy ngẫm lại về Basic binding nhé. Nó là Basic nhưng nó cũng rất quan trọng, sau này sẽ sử dụng thường xuyên trong quá trình code.

Chúc các bạn một ngày tốt lành ! 🙂

By HNK

Leave a Reply

Your email address will not be published. Required fields are marked *