mrubiosan / facade
Facade pattern ready to use
Installs: 16 727
Dependents: 1
Suggesters: 0
Security: 0
Stars: 5
Watchers: 3
Forks: 2
Open Issues: 0
Requires
- php: >=7.0
- psr/container: ^1
Requires (Dev)
- phpunit/phpunit: ^6
- squizlabs/php_codesniffer: ^2.7
This package is auto-updated.
Last update: 2024-11-14 14:41:25 UTC
README
Facade pattern for PHP
As seen in the Laravel framework. You can call a method statically, and it will fetch an object from the container and call its method.
It's very useful for unbounded services like Logging. You can call it statically but change the underlying implementation(i.e: for testing).
Also a good compromise when refactoring code that uses static class access.
Usage example
//First declare your facade class namespace MyDummyNameSpace; class Foo extends \Mrubiosan\Facade\FacadeAccessor { public static function getServiceName() { return 'foo'; //This is the name of the service in your container } }
//Then initialize the facade system $exampleContainer = new \ArrayObject([ 'foo' => new \DateTime(), ]); $psrAdaptedContainer = new \Mrubiosan\Facade\ServiceLocatorAdapter\ArrayAccessAdapter($exampleContainer); \Mrubiosan\Facade\FacadeLoader::init($psrAdaptedContainer, ['FooAlias' => 'MyDummyNameSpace\Foo']);
//Ready to use echo \MyDummyNameSpace\Foo::getTimestamp(); echo \FooAlias::getTimestamp();
Wiring it up
Step 1
If you're using a PSR11 Container, you can skip this step. Oterwise you'll need to use an adapter:
Mrubiosan\Facade\ServiceLocatorAdapter\ArrayAccessAdapter
: if you're using pimple you can use this.Mrubiosan\Facade\ServiceLocatorAdapter\CallableAdapter
: you can provide a callable parameter that will receive the service name it should retrieve.
Or straight implement Psr\Container\ContainerInterface
Step 2
Initialize the facade system
Mrubiosan\Facade\FacadeLoader::init($psrContainer);