able / facades
phpABLE 门面模式实现库
1.0.0
2021-05-31 04:11 UTC
Requires
- php: >=7.2.0
- able/static: ^1.5.0
This package is auto-updated.
Last update: 2024-09-04 12:28:06 UTC
README
phpABLE 抽象库提供了门面模式实现。
要求
- PHP >= 7.2.0
- able/statics
安装
通过Composer安装able/facades
到您的项目中有简单的方法
composer require able/facades
用法
让我们设计一个简单的类来解释门面是如何工作的
class Recipient { private $name = "Unknown"; public function __construct(string $name) { $this->name = $name; } public function changeName(string $name): void { $this->name = $name; } public function sayHello(): void { echo sprintf("Hello %s!", $this->name); } }
使用门面的目的是能够静态地调用接收者的方法,而不直接创建任何实例。在这种情况下,门面类扮演了网关的角色。我们获得的优势是代码更透明、更易于理解。
use \Able\Facades\AFacade; use \Able\Facades\Structures\SInit; class FacadeExample extends AFacade { /** * The recipient class. */ protected static $Recipient = Recipient::class; /** * The initialize method can be used to provide * some necessary arguments to the recipient class constructor if needed. */ protected final static function initialize(): SInit { return new SInit(["John"]); } } FacadeExample::sayHello(); // Hello John!
还可以将回调函数作为结构的第二个字段提供。这个函数将在创建后直接执行,并将创建的对象作为参数。
use \Able\Facades\AFacade; use \Able\Facades\Structures\SInit; class FacadeExample extends AFacade { protected static $Recipient = Recipient::class; protected final static function initialize(): SInit { return new SInit(["John"], function(Recipient $Object){ $Object->changeName("Barbara"); }); } } FacadeExample::sayHello(); // Hello Barbara!
默认情况下,将创建接收者类的唯一实例。这种行为类似于单例模式,可以通过$keepSingle
受保护的属性进行更改。
use \Able\Facades\AFacade; class FacadeExample extends AFacade { /** * If this property set to false, the new instance of the recipient object * going to be created before any method call. */ protected static $keepSingle = false; }
许可证
本软件包在MIT许可证下发布。