在 Yii2 中实现 Laravel 的 Facade

PHP技术
522
0
0
2022-11-12

新建 Facade 基类

// facades/Facade.php
namespace app\facades;

use Yii;
use yii\base\InvalidConfigException;
use yii\di\Instance;

class Facade
{
    /**
     * @return string
     * @throws InvalidConfigException
     */ 
    public static function getFacadeAccessor() {
        throw new InvalidConfigException('invalid config.');
    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     * @throws InvalidConfigException
     */ 
    public static function __callStatic($name, $arguments) {
        $service = Instance::ensure(static::getFacadeAccessor());
        return call_user_func_array([$service, $name], $arguments);
    }
}

实现 Redis Facade

只需重写类的 getFacadeAccessor 方法,此处的 redisconfig/web.php 中的 components 配置

// facades/Redis.php
namespace app\facades;


/**
 * Class Redis
 * @package app\facades
 * @method static mixed get($key)
 * @method static bool set($key, $value, $duration = null, $dependency = null)
 */
class Redis extends Facade
{
    public static function getFacadeAccessor() {
        return 'redis';
    }
}

测试

use app\facades\Redis;

public function actionIndex() {

    Redis::set('name', 'facade');
    var_dump(Redis::get('name'));

}