IdCreate.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace App\Utils;
  3. /**
  4. * Class IdCreate
  5. * @package App\Utils
  6. * 雪花算法 生成 id
  7. */
  8. class IdCreate
  9. {
  10. const EPOCH = 1479533469598; //开始时间,固定一个小于当前时间的毫秒数
  11. const max12bit = 4095;
  12. const max41bit = 1099511627775;
  13. static $machineId = null; // 机器id
  14. public static function machineId($mId = 0)
  15. {
  16. self::$machineId = $mId;
  17. }
  18. public static function createOnlyId()
  19. {
  20. // 时间戳 42字节
  21. $time = floor(microtime(true) * 1000);
  22. // 当前时间 与 开始时间 差值
  23. $time -= self::EPOCH;
  24. // 二进制的 毫秒级时间戳
  25. $base = decbin(self::max41bit + $time);
  26. // 机器id 10 字节
  27. if (!self::$machineId) {
  28. $machineid = self::$machineId;
  29. } else {
  30. $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
  31. }
  32. // 序列数 12字节
  33. $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);
  34. // 拼接
  35. $base = $base . $machineid . $random;
  36. // 转化为 十进制 返回
  37. return bindec($base);
  38. }
  39. }