mrubiosan / facade
可直接使用的外观模式
2.0.1
2019-02-27 04:00 UTC
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-09-14 14:19:26 UTC
README
PHP的外观模式
如Laravel框架所示。您可以静态调用方法,它将从容器中获取一个对象并调用其方法。
对于像日志这样的无界服务非常有用。您可以静态调用它,但可以更改底层实现(例如:用于测试)。
当重构使用静态类访问的代码时,这是一个很好的折衷方案。
使用示例
//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();
配置示例
步骤 1
如果您使用PSR11容器,可以跳过此步骤。否则,您需要使用适配器
Mrubiosan\Facade\ServiceLocatorAdapter\ArrayAccessAdapter
:如果您使用pimple,可以使用此适配器。Mrubiosan\Facade\ServiceLocatorAdapter\CallableAdapter
:您可以提供一个可调用参数,该参数将接收它应检索的服务名称。
或者直接实现 Psr\Container\ContainerInterface
步骤 2
初始化外观系统
Mrubiosan\Facade\FacadeLoader::init($psrContainer);