range

If there were you, the world would be just right

应用场景:

  • 数据库连接这种比较耗费资源的操作;
  • 我们希望整个应用只实例化一个;

结构:

  • 4私1公;
  • 私有化构造方法: 防止使用 new 创建多个实例
  • 私有化克隆方法: 防止 clone 多个实例
  • 私有化重建方法: 防止反序列化
  • 私有化静态属性: 存储对象并防止直接访问存储实例的属性
  • 公有化静态方法: 获取对象
    示例
<?php
/**
 * 类
 * Class Db
 */
class Db
{
    private static $instance = null;

    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

}
$db1 = Db::getInstance();
$db2 = Db::getInstance();


var_dump($db1);
echo '<hr>';
var_dump($db2);

打印结果
QQ截图20181031152418.jpg

普通类DB的句柄每个都是不一样的;
而单例这两个的句柄都是 1,一直是一个实例;


微信小游戏中米大师签名加密用到 HMAC-SHA256 的加密方式,此处做个备注

其他语言生成原理,大致分为这几部分:

1. 获取SHA256实例

2. 生成一个加密key

3. 通过这个加密key初始化SHA256实例

4. 根据提供的字符串,使用此实例进行加密生成hash

4. 最后整体就是转为16进制后再输出字符串

php执行起来就方便多了

function hmacsha256($data,$Key){
    $hash = hash_hmac("sha256",$data,$Key,true);
    # 转换为16进制值
    return bin2hex($hash);
}

<?php
$url = "http://local.test.com/upload.php";
$post_data = array(
    "file" => new CURLFile(realpath('1.jpg')),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
?>