Download the PHP package vaibhavpandeyvpz/datum without Composer
On this page you can find all versions of the php package vaibhavpandeyvpz/datum. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download vaibhavpandeyvpz/datum
More information about vaibhavpandeyvpz/datum
Files in vaibhavpandeyvpz/datum
Package datum
Short Description A simple Active Record ORM for PHP built on top of databoss
License MIT
Informations about the package datum
Datum
A simple Active Record ORM for PHP built on top of vaibhavpandeyvpz/databoss.
Features
- Active Record Pattern: Simple, intuitive model definitions
- Fluent Query Builder: Chain methods like
where(),sort(),limit(),offset(),get(),first() - Relationships: Support for
one(has one),many(has many),owner(belongs to), andowners(belongs to many) relationships - Attribute Casting: Automatic type conversion for DateTime, arrays, JSON, integers, floats, and booleans
- Automatic Timestamps: Automatically manages
created_atandupdated_attimestamps (enabled by default) - UUID Primary Keys: Support for UUID primary keys with automatic UUID v4 generation
- Lazy Connection Loading: Connection factory support for lazy database connection creation
- PSR-14 Event Dispatcher: Model lifecycle events (creating, created, updating, updated, deleting, deleted, saving, saved)
- Built on Databoss: Leverages the powerful databoss filtering syntax
- Multi-Database Support: Works with MySQL, PostgreSQL, SQLite, and SQL Server
- Type-safe: Full PHP 8.2+ type declarations
- Well Tested: 90%+ code coverage with comprehensive test suite
Requirements
- PHP >= 8.2
- PDO extension
- One of:
ext-pdo_mysql,ext-pdo_pgsql,ext-pdo_sqlite, orext-pdo_sqlsrv(depending on your database)
Installation
Or if you want to install the databoss dependency separately:
Quick Start
Setting Up the Connection
You can set the connection directly or use a connection factory for lazy connection creation using the connect() method:
Direct Connection
Connection Factory (Lazy Loading)
Defining a Model
Basic CRUD Operations
Automatic Timestamps
Datum automatically manages created_at and updated_at timestamps by default. When you save a model:
- On Insert: Both
created_atandupdated_atare automatically set to the current timestamp - On Update: Only
updated_atis automatically updated
Disabling Timestamps:
If you want to disable automatic timestamps for a model, set the $timestamps property to false:
Custom Timestamp Column Names:
You can customize the timestamp column names:
Manually Setting Timestamps:
You can still manually set timestamps, and they will be respected:
Using PSR-20 Clock:
Datum uses PSR-20 ClockInterface for timestamp generation, allowing you to inject a custom clock implementation for testing or time manipulation:
For testing, you can use vaibhavpandeyvpz/samay to control time:
UUID Primary Keys
Datum supports UUID (Universally Unique Identifier) primary keys in addition to auto-incrementing integer IDs. When using UUIDs, Datum will automatically generate a UUID v4 before inserting the model into the database.
Setting Up a Model with UUID Primary Key:
Database Schema Example:
For MySQL:
For PostgreSQL:
For SQLite:
Usage:
Key Points:
- Set
protected static bool $incrementing = false;to enable UUID primary keys - Set
protected static string $primaryKey = 'uuid';(or your UUID column name) - UUIDs are automatically generated as UUID v4 if not provided
- You can manually set UUIDs if needed
- All standard operations (find, update, delete) work with UUIDs
Attribute Casting
Datum supports automatic type casting for attributes. Define casts in your model's $casts property:
Supported Cast Types:
intorinteger- Casts to integerfloatordouble- Casts to floatboolorboolean- Casts to boolean (stored as 0/1 in database)string- Casts to stringarrayorjson- Automatically JSON encodes/decodesdatetimeordate- Casts to/fromDateTimeobjects
Example:
Querying
Relationships
Has One
Has Many
Belongs To (Owner)
Belongs To Many (Owners)
Model Events
Datum supports PSR-14 compliant event dispatching, allowing you to hook into model lifecycle events. Events are fired at key points during model operations, giving you the ability to perform actions like logging, validation, or side effects.
Setting Up the Event Dispatcher:
You can set the dispatcher directly or use a factory for lazy dispatcher creation:
Available Events:
Datum fires the following events during model operations:
Datum\Events\Saving- Fired before saving (both create and update)Datum\Events\Saved- Fired after saving (both create and update)Datum\Events\Creating- Fired before creating a new modelDatum\Events\Created- Fired after creating a new modelDatum\Events\Updating- Fired before updating an existing modelDatum\Events\Updated- Fired after updating an existing modelDatum\Events\Deleting- Fired before deleting a modelDatum\Events\Deleted- Fired after deleting a model
Event Order:
When saving a new model:
SavingeventCreatingevent- Database insert
CreatedeventSavedevent
When updating an existing model:
SavingeventUpdatingevent- Database update
UpdatedeventSavedevent
When deleting a model:
Deletingevent- Database delete
Deletedevent
Listening to Events:
All events implement Psr\EventDispatcher\StoppableEventInterface, allowing you to stop event propagation if needed:
Stopping Event Propagation:
You can stop event propagation to abort an operation:
Complete Example:
Using with Dependency Injection:
Advanced Filtering
Datum supports all databoss filter syntax:
API Reference
Model Static Properties
protected static ?string $table- The table name (auto-inferred from class name if not set)protected static string $primaryKey- The primary key column name (default:'id')protected static bool $incrementing- Indicates if the IDs are auto-incrementing (default:true). Set tofalsefor UUID primary keysprotected static array $casts- Attribute casting configurationprotected static bool $timestamps- Enable/disable automatic timestamp management (default:true)protected static string $createdAt- The name of the "created at" column (default:'created_at')protected static string $updatedAt- The name of the "updated at" column (default:'updated_at')
Model Static Clock Methods
Model::clock(ClockInterface $clock)- Set a PSR-20 clock instance for timestamp generation
Model Static Event Dispatcher Methods
Model::dispatcher(EventDispatcherInterface|callable|null $dispatcherOrFactory)- Set the PSR-14 event dispatcher instance, factory, ornullto clear
Model Static Methods
Model::connect(ConnectionInterface|callable(): ConnectionInterface $connectionOrFactory)- Set the database connection directly or use a factory for lazy connection creationModel::query()- Create a new query builder instanceModel::where(array $conditions)- Create a query with WHERE conditionsModel::find(int|string $id)- Find a model by primary key (returnsnullif not found)Model::findOrFail(int|string $id)- Find a model or throwRuntimeExceptionif not foundModel::all()- Get all models from the tableModel::first()- Execute the query and return the first model
Model Instance Methods
$model->save()- Save the model to database (inserts if new, updates if exists)$model->delete()- Delete the model from database$model->exists()- Check if model exists in database$model->key()- Get the primary key value$model->toArray()- Convert model to array (with casts applied)$model->attribute(string $key)- Get an attribute value (with casting)$model->assign(string $key, mixed $value)- Set an attribute value (with casting)$model->attributes()- Get all attributes as array (raw, without casting)$model->freshTimestamp()- Get a fresh timestamp string (used internally for automatic timestamps)
Builder Methods
where(array $conditions)- Add WHERE conditions (supports databoss filter syntax)sort(string $column, string $direction = 'ASC')- Add ORDER BY clauselimit(int $limit)- Set LIMIT clauseoffset(int $offset)- Set OFFSET clauseget()- Execute and return all results (returnsarray|false)first()- Execute and return first result (returnsobject|array|false)count()- Count matching records (returnsint|false)exists()- Check if any records exist (returnsbool)recreate()- Get a fresh instance of the query builder
Relationship Methods
one(string $related, string $foreignKey, string $localKey = 'id')- Define has one relationshipmany(string $related, string $foreignKey, string $localKey = 'id')- Define has many relationshipowner(string $related, string $foreignKey, string $ownerKey = 'id')- Define belongs to relationship (this model is owned by another)owners(string $related, string $pivotTable, string $foreignPivotKey, string $relatedPivotKey, string $parentKey = 'id', string $relatedKey = 'id')- Define belongs to many relationship (this model is owned by many)
Property Access
Models support magic property access for attributes and relationships:
Examples
Complete Example
Testing
The project includes Docker Compose configuration for running tests:
Tests run against MySQL, PostgreSQL, SQLite, and SQL Server to ensure compatibility across all supported databases.
The test suite includes:
- 163+ tests
- 426+ assertions
- 90%+ code coverage
- Tests for all CRUD operations
- Tests for all relationship types
- Tests for attribute casting
- Tests for query builder methods
- Edge case and error handling tests
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License - see LICENSE file for details.
All versions of datum with dependencies
psr/clock Version ^1.0
psr/event-dispatcher Version ^1.0
vaibhavpandeyvpz/databoss Version ^2.1