php8.0新特性:命名参数

2023年9月2日10:19:00

<?php

namespace App\Services\Admin;

use DateTime;

class GeneratorService
{
    //订单key前缀
    const ORDER = 'Z_';
    //支付key前缀
    const DOPAY = 'PAY_';

    const KEY_LENGTH = 27;

    // 返回数据固定长度 29
    public static function getRandKey()
    {
        list($usec, $sec) = explode(" ", microtime());
        list($zero, $u) = explode('.', $usec);
        $time = date('YmdHis', $sec) . $u;
        //随机数
        $randval = rand(100, 999) . rand(100, 999);
        return $time . $randval;
    }

    //算法明发性能一般,线上建议优化
    public static function getNewRandKey()
    {
        $dateTime = new DateTime();
        $time = $dateTime->format('YmdHisu');
        //随机数
        $randval = rand(100, 999) . rand(100, 999);
        return $time . $randval;
    }

    public static function getUniqKey(string $format = 'YmdHisu', string $prefix = '')
    {
        $dateTime = new DateTime();
        $time = $dateTime->format($format);
        $randval = uniqid();

        return empty($prefix) ? $time . $randval : $prefix . $time . $randval;
    }

    //通用订单号生产
    public static function getOrderKey()
    {
        return self::ORDER . self::getNewRandKey();
    }

    //通用支付订单号生产
    public static function getPayKey()
    {
        return self::DOPAY . self::getNewRandKey();
    }

    public static function getShortKey()
    {
        return strtoupper(uniqid() . rand(100, 999));
    }

}

调用的时候通常是:

   $r = GeneratorService::getUniqKey('YmdHisu', 'zx');
   p($r);

   $r = GeneratorService::getShortUniqKey(prefix: 'zx', format: 'YmdHisu');
   p($r);

   $r = GeneratorService::getShortUniqKey(prefix: 'zx', format: 'YmdHisu');
   p($r);
   
   $r = GeneratorService::getShortUniqKey(prefix: 'zx');
   p($r);

这样就可以不用去写每个参数的变量名,这样可以减少一些操作

posted on 2023-09-02 10:23  zh7314  阅读(57)  评论(0编辑  收藏  举报