Download the PHP package mjkhajeh/wporm without Composer
On this page you can find all versions of the php package mjkhajeh/wporm. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mjkhajeh/wporm
More information about mjkhajeh/wporm
Files in mjkhajeh/wporm
Package wporm
Short Description WPORM is a lightweight, Eloquent-inspired ORM for WordPress plugins and themes. It provides expressive, fluent query building, model relationships, schema management, attribute casting, and event hooks—while fully supporting the WordPress database API and table prefixing. WPORM makes it easy to build modern, maintainable database code in any WordPress project.
License MIT
Informations about the package wporm
WPORM - Lightweight WordPress ORM
WPORM is a lightweight Object-Relational Mapping (ORM) library for WordPress plugins. It provides an Eloquent-like API for defining models, querying data, and managing database schema, all while leveraging WordPress's native $wpdb
database layer.
Documentation
- Methods list and documents
- Blueprint and column types documents
- Casts types and define custom casts
- DB usage and raw queries
- Debugging tips
Features
- Model-based data access: Define models for your tables and interact with them using PHP objects.
- Schema management: Create and modify tables using a fluent schema builder.
- Query builder: Chainable query builder for flexible and safe SQL queries.
- Attribute casting: Automatic type casting for model attributes.
- Relationships: Define
hasOne
,hasMany
,belongsTo
,belongsToMany
, andhasManyThrough
relationships. - Events: Hooks for model lifecycle events (creating, updating, deleting).
- Global scopes: Add global query constraints to models.
Installation
With Composer (Recommended)
You can install WPORM via Composer. In your plugin or theme directory, run:
Then include Composer's autoloader in your plugin bootstrap file:
Manual Installation
- Place the
ORM
directory in your plugin folder. - Include the ORM in your plugin bootstrap:
Defining a Model
Create a model class extending MJ\WPORM\Model
:
Note: When using
$table
in custom SQL queries, do not manually add the WordPress prefix (e.g.,$wpdb->prefix
). The ORM automatically handles table prefixing. Use$table = (new User)->getTable();
as shown in the next, which returns the fully-prefixed table name.
Schema Management
Create or update tables using the model's up
method and the SchemaBuilder
:
Unique Indexes (Eloquent-style)
You can add a unique index to a column using Eloquent-style chaining:
For multi-column unique indexes, use:
This works for all column types and matches Eloquent's API.
Basic Usage
Creating a Record
Querying Records
Querying by a Specific Column
You can easily retrieve records by a specific column using the query builder's where
method. For example, to get all parts with a specific product_id
:
Or, to get the first user by email:
You can also use other comparison operators:
This approach works for any column in your table.
Creating or Updating Records: updateOrCreate
WPORM provides an updateOrCreate
method, similar to Laravel Eloquent, for easily updating an existing record or creating a new one if it doesn't exist.
Usage:
- The first argument is an array of attributes to search for.
- The second argument is an array of values to update or set if creating.
- The optional third argument disables global scopes if set to
false
(default istrue
). - Returns the updated or newly created model instance.
This is useful for upsert operations, such as syncing data or ensuring a record exists with certain values.
Creating or Getting Records: firstOrCreate and firstOrNew
WPORM also provides firstOrCreate
and firstOrNew
methods, similar to Laravel Eloquent, for convenient record retrieval or creation.
firstOrCreate Usage:
- Returns the first matching record, or creates and saves a new one if none exists.
- The optional third argument disables global scopes if set to
false
(default istrue
).
firstOrNew Usage:
- Returns the first matching record, or a new (unsaved) instance if none exists.
- The optional third argument disables global scopes if set to
false
(default istrue
).
These methods are useful for ensuring a record exists, or for preparing a new record with default values if not found.
Updating a Record
Deleting a Record
Pagination
WPORM supports Eloquent-style pagination with the following methods on the query builder:
paginate($perPage = 15, $page = null)
Returns a paginated result array with total count and page info:
simplePaginate($perPage = 15, $page = null)
Returns a paginated result array without total count (more efficient for large tables):
See Methods.md for more details and options.
Attribute Casting
Add a $casts
property to your model:
Array Conversion and Casting
- Call
->toArray()
on a model or a collection to get an array representation with all casts applied. - Built-in types (e.g. 'int', 'bool', 'float', 'json', etc.) are handled natively and will not be instantiated as classes.
- Custom cast classes must implement
MJ\WPORM\Casts\CastableInterface
.
Example:
- Custom cast classes will be instantiated and their
get()
method called. - Built-in types will be cast using native PHP logic.
Relationships
WPORM supports Eloquent-style relationships. You can define them in your model using the following methods:
-
hasOne: One-to-one
-
hasMany: One-to-many
-
belongsTo: Inverse one-to-one or many
-
belongsToMany: Many-to-many (with optional pivot table and keys)
- hasManyThrough: Has-many-through
All relationship methods return either a model instance or a Collection
of models. You can use them just like in Eloquent.
Relationship Existence Filtering: whereHas, orWhereHas, has
whereHas('relation', function($q) { ... })
: Filter models where the relation exists and matches constraints.orWhereHas('relation', function($q) { ... })
: OR version of whereHas.has('relation', '>=', 2)
: Filter models with at least (or exactly, or at most) N related records. Operator and count are optional (defaults to ">= 1").
Examples:
Custom Attribute Accessors/Mutators
Appended (Computed) Attributes
You can add computed (virtual) attributes to your model's array/JSON output using the $appends
property, just like in Eloquent.
- Appended attributes are included in
toArray()
and JSON output. - The value is resolved via a
get{AttributeName}Attribute()
accessor or, if not present, by a public property. - Do not set appended attributes in
retrieved()
; use accessors instead.
Transactions
Custom Queries
You can execute custom SQL queries using the underlying $wpdb
instance or by extending the model/query builder. For example:
You can also add custom static methods to your model for more complex queries:
Raw Table Queries with DB::table()
WPORM now supports Eloquent-style raw table queries using the DB
class:
See DB.md for more details.
Complex Where Statements
WPORM now supports complex nested where/orWhere statements using closures, similar to Eloquent:
You can still use multiple where
calls for AND logic, and orWhere
for OR logic:
Note: For very advanced SQL, you can always use
$wpdb
directly.You can also use
$wpdb
directly for complex SQL logic:
Using newQuery()
The newQuery()
method returns a fresh query builder instance for your model. This is useful when you want to start a new query chain, especially in custom scopes or advanced use cases. It is functionally similar to query()
, but is a common convention in many ORMs.
Example:
You can use newQuery()
anywhere you would use query()
. Both methods are available for convenience and compatibility with common ORM patterns.
Timestamp Columns
You can customize how WPORM handles timestamp columns in your models. By default, models will automatically manage created_at
and updated_at
columns if $timestamps = true
(the default).
Example: Customizing Timestamp Column Names
With this setup, WPORM will automatically set created_on
and changed_on
when you create or update an Article
record.
Example: Disabling Timestamps
If you do not want WPORM to manage any timestamp columns, set $timestamps = false
in your model:
In this case, WPORM will not attempt to set or update any timestamp columns automatically.
Global Scopes
You can define global scopes on your model to automatically apply query constraints to all queries for that model.
Example:
All queries will now include status = 'published'
automatically:
To disable global scopes for a query:
To remove a specific global scope at runtime:
Soft Deletes
WPORM supports Eloquent-style soft deletes, allowing you to "delete" records without actually removing them from the database. To enable soft deletes on a model, set the $softDeletes
property to true
:
Soft Delete Strategies: Timestamp vs Boolean Flag
WPORM supports two soft delete strategies:
-
Timestamp column (default, Eloquent-style):
- Uses a
deleted_at
(or custom) column to store the deletion datetime. - Set
$softDeletes = true;
and (optionally)$deletedAtColumn = 'deleted_at';
in your model. -
Example:
- In your migration/schema:
- Uses a
-
Boolean flag column:
- Uses a boolean column (e.g.,
deleted
) to indicate soft deletion (1
= deleted,0
= not deleted). - Set
$softDeletes = true;
,$deletedAtColumn = 'deleted'
, and$softDeleteType = 'boolean';
in your model. -
Example:
- In your migration/schema:
- Uses a boolean column (e.g.,
How it works
- Timestamp mode:
delete()
setsdeleted_at
to the current datetime.restore()
setsdeleted_at
tonull
.- Queries exclude rows where
deleted_at
is not null (unlesswithTrashed()
oronlyTrashed()
is used).
- Boolean mode:
delete()
setsdeleted
to1
(true).restore()
setsdeleted
to0
(false).- Queries exclude rows where
deleted
is true (unlesswithTrashed()
oronlyTrashed()
is used).
Example Usage
Troubleshooting & Tips
- Table Prefixing: Always use
$table = (new ModelName)->getTable();
to get the correct, prefixed table name for custom SQL. Do not manually prepend$wpdb->prefix
. - Model Booting: If you add static boot methods or global scopes, ensure you call them before querying if not using the model's constructor.
- Schema Changes: If you change your model's
up()
schema, you may need to drop and recreate the table or use theSchemaBuilder
'stable()
method for migrations. - Events: You can add
creating
,updating
, anddeleting
methods to your models for event hooks. - Extending Casts: Implement
MJ\WPORM\Casts\CastableInterface
for custom attribute casting logic. - Testing: Always test your queries and schema changes on a staging environment before deploying to production.
Contributing
Contributions, bug reports, and feature requests are welcome! Please open an issue or submit a pull request.
Credits
WPORM is inspired by Laravel's Eloquent ORM and adapted for the WordPress ecosystem.
Version
- Current Version: 1.0.0
- Changelog:
- Initial release with full Eloquent-style ORM features for WordPress.
Security Note
- Always validate and sanitize user input, even when using the ORM. The ORM helps prevent SQL injection, but you are responsible for data integrity and security.
Performance Tips
- Use indexes for columns you frequently query (e.g., foreign keys, search fields). The ORM's schema builder supports
$table->index('column')
. - For large datasets, use pagination and limit/offset queries to avoid memory issues:
FAQ
Q: Why is my table not created?
- A: Ensure your model's
up()
method is correct and that you call the schema builder. Check for errors in your SQL or schema definition.
Q: How do I debug a failed query?
- A: Use
$wpdb->last_query
and$wpdb->last_error
after running a query to inspect the last executed SQL and any errors.
Q: Can I use this ORM outside of WordPress?
- A: No, it is tightly coupled to WordPress's
$wpdb
and plugin environment.
Resources
License Details
This project is licensed under the MIT License. See the LICENSE file or MIT License for details.