Skip to content

Instantly share code, notes, and snippets.

@marcojetson
Created July 24, 2015 15:06
Show Gist options
  • Save marcojetson/1c7f8377737cbf47c397 to your computer and use it in GitHub Desktop.
Save marcojetson/1c7f8377737cbf47c397 to your computer and use it in GitHub Desktop.
Mongo inspired unique and sortable id generation
<?php
class ObjectId
{
/** @var string */
private $value;
/**
* @param string $value
*/
public function __construct($value = null)
{
$this->value = $value ? : static::generate();
}
/**
* @return string
*/
public function valueOf()
{
return $this->value;
}
/**
* @return string
*/
public function getTimestamp()
{
$sec = hexdec(substr($this->value, 0, 8));
$usec = hexdec(substr($this->value, 8, 7));
return $sec . '.' . $usec;
}
/**
* @return int
*/
public function compareTo($other)
{
$ts1 = $this->getTimestamp();
$ts2 = $other->getTimestamp();
if ($ts1 > $ts2) {
return 1;
}
if ($ts1 < $ts2) {
return -1;
}
return 0;
}
/**
* @return string
*/
public function __toString()
{
return sprintf('%s(%s)', get_class($this), $this->valueOf());
}
/**
* @return string
*/
public static function generate()
{
list($usec, $sec) = explode(' ', microtime());
return sprintf('%08x%07x%05x', $sec, substr($usec, 2), mt_rand(0, 0xfffff));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment