A feature-packed, standalone ObjectId implementation for PHP.
SlimeSystems\ObjectId provides a BSON-compatible identifier generator and utility class, fully compliant with the MongoDB ObjectId specification.
It is lightweight, requires no external extensions (like mongodb), and is perfect for generating sortable, unique identifiers in any PHP application.
Install via Composer:
composer require slime-systems/object-iduse SlimeSystems\ObjectId;
// Generate a new unique ID
$id = new ObjectId();
echo $id;
// Output: 507f1f77bcf86cd799439011
// Get the generation time
$timestamp = $id->toTime();
// Returns a DateTime objectCreate a fresh, unique 12-byte identifier.
$id = new ObjectId;Restore an ObjectId from its 24-character hexadecimal representation.
$id = ObjectId::fromString('507f1f77bcf86cd799439011');Create from a raw 12-byte binary string (e.g., stored in a database).
$id = ObjectId::fromBinary($binaryData);Generate an ID based on a specific time. useful for time-based sorting or filtering.
// From a DateTime object
$id = ObjectId::fromTime(new DateTime('2025-01-01'));
// From a Unix timestamp
$id = ObjectId::fromTime(1735689600);Note: By default, fromTime generates a unique ID (randomizing the remaining bytes). If you need a "zeroed" ID for range queries (e.g., "find all IDs created after X"), pass unique: false:
$startId = ObjectId::fromTime($timestamp, unique: false);
// Last 8 bytes will be 0000000000000000Invalid input to the ObjectId::from... series will throw SlimeSystems\ObjectId\Exception\Invalid.
They are safe for handling untrusted variables, assuming that this exception is the expected behavior.
$id = new ObjectId;
// To Hex String (24 chars)
$hex = $id->toString();
// or simply: (string) $id
// To Binary (12 bytes)
$bin = $id->toBinary();
// To DateTime
$date = $id->toTime();Check if two ObjectIds represent the same value.
if ($id1->equals($id2)) {
// ...
}Compare two IDs lexicographically (useful for sorting).
$result = $id1->compareTo($id2);
// -1 if $id1 < $id2
// 0 if $id1 == $id2
// 1 if $id1 > $id2Get a readable inspection string.
echo $id->inspect();
// SlimeSystems\ObjectId(507f1f77bcf86cd799439011)Using Laravel? Check out SlimeSystems\EloquentObjectId for seamless integration with Eloquent models.
Run the test suite with:
composer run testOr if you have containerd:
make testThis project is licensed under the BSD 2-Clause License.