Advanced Container Package for Laravel

Packages

October 1st, 2021

laravel-enhanced-container-featured.png

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 binding
2bind(ServiceInterface::class)->to(Service::class);
3 
4// Singleton
5bind(ServiceInterface::class)->singleton(Service::class);
6 
7// Scoped instance
8bind(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 behavior
10bind(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.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.