zhangshize / slim-facades
Slim 3 & 4 的 Facades。
Requires
- php: >=5.5.0
- slim/slim: >=3.0
This package is not auto-updated.
Last update: 2024-09-26 13:27:50 UTC
README
简介
SlimFacades 是一个包,为 Slim PHP 框架 提供 Facades。
Facades 是来自 Laravel(也是一个 PHP 框架) 的名词。Facades 提供了对应用程序服务容器中可用的类的“静态”接口。
Laravel 的 Facades 作为服务容器中底层类的“静态代理”,提供了简洁、表达性强的语法,同时比传统的静态方法具有更多的可测试性和灵活性,Slim-Facades 也是如此。
要求
- PHP >= 5.5.0
- Slim >= 3.0
安装
使用 composer
composer require zhangshize/slim-facades
使用方法
安装后,你可以像这样更新你的代码
//... Something not important ... use SlimFacades\Facade; use SlimFacades\Route; use SlimFacades\App; $app = new \Slim\App(/*...*/); // initialize the Facade class Facade::setFacadeApplication($app); Route::get('/', function (Request $req, Response $res) { $res->getBody()->write("Hello"); return $res; }); App::run();
默认 Facades
Slim-Facades 提供以下 Facades
App
就像使用 $app 一样使用它!
App::run();
Container
就像使用 $container 一样使用它!
Container::hasService('view');
Route
Route::get('/', function (Request $req, Response $res) { $res->getBody()->write("Hello"); return $res; });
Request
$method = Request::getMethod();
Response
Response::withStatus(302);
Setting
以下是一些特殊方法
get($key = null)
/** * Get the settings value. * If $key = null, this function returns settings. * @param string|null $key * @return mixed */ public static function get($key = null) { // ... }
使用方法
Settings::get()['db']; Settings::get('db'); //The same result.
set($key, $value)
/** * Set the settings value. * When $key is an array, it will be viewed to a list of keys. <br> * For Example: * $key = ['a','b']; <br> * The function will set the value of $container->settions['a']['b']. * @param array|string $key * @param mixed $value */ public static function set($key, $value) { // ... }
使用方法
$container['settings']['db']['host'] = 'localhost'; Settings::set(['db', 'host'], 'localhost'); //The same result.
视图和日志
如果你想使用它们,你应该在容器中设置 'view' 和 'logger' 服务,或者更改由 getFacadeAccessor()
返回的值。
自定义 Facades
为容器中的服务创建自定义 Facades 的代码如下
using SlimFacades\Facade; class CustomFacade extends Facade { protected static function getFacadeAccessor() { //Change 'serviceName' to you want. return 'serviceName'; } }
为实例创建自定义 Facades 的代码如下
using SlimFacades\Facade; class CustomFacade extends Facade { public static function self() { //Change the returned value to you want. return self::$app->getContainer()->get('myservice'); } }
许可证
版权 [2016] [zhangshize]
根据 Apache License, Version 2.0 (“许可证”) 许可;除非适用法律要求或书面同意,否则不得使用此文件,除非符合许可证。您可以在以下位置获得许可证的副本:
https://apache.ac.cn/licenses/LICENSE-2.0
除非适用法律要求或书面同意,否则在许可证下分发的软件按“原样”基础分发,不提供任何明示或暗示的保证或条件。有关许可证的具体语言规定权限和限制,请参阅许可证。