I need to know what is the purpose of using service container's tagging and how to use it by example this is what I have tried so far.
class MemoryReport
{
}
class SpeedReport
{
}
class ReportAggregator
{
public function __construct(MemoryReport $memory, SpeedReport $speed)
{
}
}
App::bind('MemoryReport', function () {
return new MemoryReport;
});
App::bind('SpeedReport', function () {
return new SpeedReport;
});
App::tag(['MemoryReport', 'SpeedReport'], 'reports');
App::bind('ReportAggregator', function ($app) {
return new ReportAggregator($app->tagged('reports'));
});
$reportAggregator = resolve('ReportAggregator');
dd($reportAggregator);
This is the error I get.
Argument 1 passed to ReportAggregator::__construct() must be an instance of MemoryReport, instance of Illuminate\Container\RewindableGenerator given, called in /media/mazzam/9068A9DC68A9C0F81/M.azzam/Learning/laravel/00 Tutorial/tut/routes/web.php on line 80
According to the documentation, tagging is used to resolve a certain "category" of binding.
I will explain what does this means by showing you some code from one of our projects.
We use several OCR systems to scan the uploaded documents:
App\Support\OCR\GoogleVision
App\Support\OCR\AmazonTextract
App\Support\OCR\Tesseract
...All these classes implement the
App\Contracts\OCR
interface:We grouped all the OCR(s) into a tag named
ocrs
:Then we inject the
ocrs
tag into theScan
object as follows:As you might have noticed, we've used the array spread operator
...
which spreads the array elements and pass them individually to theScan
object.Let's see how the
Scan
class looks like:The Scan's contractor uses the argument unpacking (variadic) which means that we can pass N number of objects that implementing the
App\Contracts\OCR
.You may be wondering, why didn't use type-hinting instead of tagging?
That's because we constantly add/remove OCR systems based on the customer's needs.
So, by using the tags, we are not tied to specific implementations, since we can easily add/remove the classes based on the customer's needs.
I hope, I answered your question.