Advanced Container for Laravel is a package that provides syntax sugars for Laravel container calls, bindings, and more.
Here's an example of binding services, singletons, and scoped interfaces with this package:
1// Basic binding2bind(ServiceInterface::class)->to(Service::class);3 4// Singleton5bind(ServiceInterface::class)->singleton(Service::class);6 7// Scoped instance8bind(ServiceInterface::class)->scoped(Service::class);
With this package, you can do method binding using the package's syntax sugar to do things like perform calls to your service through the container and override method behavior:
1// Basic call to a service through the container 2call(Service::class)->yourMethod(100) 3 4// Override the method behavior 5bind(Service::class)->method()->yourMethod(function ($service, $app, $params) { 6 return $service->yourMethod($params['count']) + 1; 7}); 8 9// Alternative syntax to bind method behavior10bind(Service::class)->method('yourMethod', function ($service, $app, $params) {11 return $service->yourMethod($params['count']) + 1;12});
Using this package, you can easily mock methods in your tests as well:
1bind(ServiceInterface::class)->method( 2 'externalApiRequestReturnsFalse', 3 fn () => false 4); 5 6$service = call(ServiceInterface::class); 7 8$call = $service->externalApiRequestReturnsFalse(); 9 10$this->assertFalse($call);
This package also supports method forwarding—check the README for details. You can learn more about this package, get full installation instructions, and view the source code on GitHub.
0 comments:
Post a Comment
Thanks