An open API service indexing awesome lists of open source software.

https://github.com/misits/wordpress-orm

A modern Laravel Eloquent-inspired ORM for WordPress that provides clean database interaction patterns while maintaining full WordPress ecosystem compatibility.
https://github.com/misits/wordpress-orm

orm wordpress wordpress-orm wp

Last synced: 5 months ago
JSON representation

A modern Laravel Eloquent-inspired ORM for WordPress that provides clean database interaction patterns while maintaining full WordPress ecosystem compatibility.

Awesome Lists containing this project

README

          

# WordPress ORM

A modern Laravel Eloquent-inspired ORM for WordPress that provides clean database interaction patterns while maintaining full WordPress ecosystem compatibility.

## ✨ Features

- **🚀 Modern Laravel-style Syntax** - Clean, intuitive Eloquent-like API
- **⚡ Optimized Performance** - Superior performance for complex queries and large datasets
- **🔗 WordPress Integration** - Full compatibility with WordPress core tables and ecosystem
- **🛠️ Dual Table Support** - Works with both custom tables and WordPress default tables
- **🔍 Advanced Query Builder** - Fluent interface with method chaining
- **📊 Schema Management** - Laravel-style migrations and table management
- **⚙️ Powerful CLI** - WP-CLI integration with Artisan-style commands
- **🌱 Database Seeding** - Populate databases with realistic test data
- **🔐 Security First** - Built-in protection against SQL injection
- **📈 Scalable** - Optimized for sites from small blogs to enterprise applications

## 🚀 Quick Start

### Installation

**Plugin Integration:**
```php
// In your plugin's main file
require_once plugin_dir_path(__FILE__) . 'lib/wp-orm/bootstrap.php';
```

**Theme Integration:**
```php
// In your theme's functions.php
require_once get_template_directory() . '/lib/wp-orm/bootstrap.php';
```

### WordPress Content Management

WordPress ORM provides ready-to-use models for all WordPress core tables:

```php
use WordPressORM\Models\{Post, Page, User, Comment};

// Create a new post
$post = Post::create([
'post_title' => 'My First Post',
'post_content' => 'This is the content',
'post_status' => 'publish',
'post_type' => 'post'
]);

// Query WordPress content
$posts = Post::where('post_status', 'publish')
->where('post_type', 'post')
->latest('post_date')
->limit(10)
->get();

// Create WordPress users
$user = User::create([
'user_login' => 'johndoe',
'user_email' => 'john@example.com',
'display_name' => 'John Doe'
]);
```

### Custom Tables

WordPress ORM excels at creating and managing custom tables for advanced applications:

```php
use WordPressORM\ORM\{Model, Schema\Schema};

// Define your custom model
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['name', 'price', 'category', 'description', 'status'];
protected $casts = [
'price' => 'decimal:2',
'is_featured' => 'boolean'
];
}

// Create the table with advanced schema
Schema::create('products', function($table) {
$table->id();
$table->string('name');
$table->string('category')->index();
$table->decimal('price', 10, 2);
$table->text('description');
$table->boolean('is_featured')->default(false);
$table->enum('status', ['draft', 'published', 'archived'])->default('draft');
$table->timestamps();

// Add indexes for performance
$table->index(['status', 'is_featured']);
$table->index('created_at');
});

// Advanced usage with relationships and scopes
$products = Product::where('status', 'published')
->where('is_featured', true)
->where('price', '>', 10.00)
->orderBy('created_at', 'desc')
->limit(10)
->get();

// Create with validation
$product = Product::create([
'name' => 'Premium WordPress Theme',
'category' => 'themes',
'price' => 59.99,
'description' => 'A beautiful, responsive theme',
'is_featured' => true,
'status' => 'published'
]);
```

### Benefits of Custom Tables
- **🚀 Performance** - Optimized schemas for your specific data
- **🔧 Flexibility** - Design tables exactly for your needs
- **📊 Advanced Queries** - Complex relationships and filtering
- **🛡️ Data Integrity** - Foreign keys and constraints
- **📈 Scalability** - Handle millions of records efficiently

## ⚙️ Command Line Interface

WordPress ORM includes a comprehensive CLI built on WP-CLI, bringing Laravel Artisan-style commands to WordPress development:

### Quick CLI Examples

```bash
# Create and run migrations
wp borps orm:make-migration create_products_table --create=products --model=Product
wp borps orm:migrate --seed

# Generate models and seeders
wp borps orm:make-model Category --migration
wp borps orm:make-seeder ProductSeeder

# Database operations
wp borps orm:migrate-refresh --seed # Fresh start with test data
wp borps orm:db-seed --class=ProductSeeder # Run specific seeder
wp borps orm:migrate-status # Check migration status

# Development workflow
wp borps orm:migrate-rollback --steps=2 # Undo last 2 migrations
```

### Available Commands

| Command | Description |
|---------|-------------|
| `wp borps orm:migrate` | Run pending migrations |
| `wp borps orm:migrate-status` | Show migration status |
| `wp borps orm:migrate-rollback` | Rollback migrations |
| `wp borps orm:migrate-refresh` | Reset and re-run all migrations |
| `wp borps orm:migrate-reset` | Drop all ORM tables |
| `wp borps orm:make-migration` | Create new migration |
| `wp borps orm:make:-model` | Generate model class |
| `wp borps orm:make-seeder` | Create database seeder |
| `wp borps orm:db-seed` | Run database seeders |
| `wp borps orm:help` | Show detailed help |

### Laravel-Style Development Workflow

```bash
# 1. Create feature with model and migration
wp borps orm:make-migration create_products_table --create=products --model=Product

# 2. Add fields and relationships
wp borps orm:make-migration add_category_to_products --table=products

# 3. Run migrations
wp borps orm:migrate

# 4. Create test data
wp borps orm:make-seeder ProductSeeder
wp borps orm:db-seed

# 5. Fresh start when needed
wp borps orm:migrate-refresh --seed
```

For complete CLI documentation, see **[CLI Commands Guide](docs/cli.md)**.

## 📚 Documentation

Comprehensive documentation is available in the `/docs` directory:

### Core Documentation
- **[Installation Guide](docs/installation.md)** - Complete setup instructions for plugins and themes
- **[Configuration](docs/configuration.md)** - Environment setup and customization options
- **[Models](docs/models.md)** - Creating and using Eloquent-style models
- **[Query Builder](docs/queries.md)** - Advanced querying techniques and methods
- **[Relationships](docs/relationships.md)** - Setting up model relationships
- **[Migrations](docs/migrations.md)** - Database schema management
- **[CLI Commands](docs/cli.md)** - WP-CLI integration and command reference
- **[WordPress Integration](docs/wordpress-integration.md)** - Working with WordPress core tables

### Quick Examples
- **[Examples](docs/examples.md)** - Practical usage examples and patterns

## 🌟 WordPress Integration

WordPress ORM provides seamless integration with all WordPress core tables through pre-built models:

### WordPress Models Available
- **Post** - `wp_posts` (all post types: posts, pages, custom post types)
- **Page** - Specialized Post model for WordPress pages
- **User** - `wp_users` (WordPress user management)
- **Comment** - `wp_comments` (post comments and reviews)
- **Option** - `wp_options` (WordPress settings and configuration)
- **Term** - `wp_terms` (categories, tags, taxonomy terms)
- **Taxonomy** - `wp_term_taxonomy` (taxonomy relationships)
- **Meta Models** - PostMeta, UserMeta, CommentMeta, TermMeta

### Performance Benefits
- **~6x Faster** than WordPress native queries
- **Direct Database Access** bypassing WordPress query overhead
- **No Plugin Interference** from caching or SEO plugins
- **Optimized SQL Generation** for better performance

### WordPress Compatibility
- ✅ **Full Ecosystem Integration** - Works alongside existing WordPress
- ✅ **Plugin Compatible** - Data remains accessible to other plugins
- ✅ **Theme Compatible** - Frontend queries continue working
- ✅ **Admin Compatible** - WordPress admin interfaces work normally

## 🎯 Why Use WordPress ORM

WordPress ORM brings modern development practices to WordPress:

### Developer Experience Benefits
```php
// Clean, readable syntax
$posts = Post::where('post_status', 'publish')
->where('post_type', 'post')
->with('author', 'comments')
->orderBy('post_date', 'desc')
->get();

// Compare to WordPress native
$posts = get_posts([
'post_status' => 'publish',
'post_type' => 'post',
'meta_query' => [...], // Complex array structure
'orderby' => 'date',
'order' => 'DESC'
]);
```

### Custom Tables Made Easy
```php
// WordPress has no equivalent for custom tables
$analytics = Analytics::whereDate('created_at', today())
->whereIn('event_type', ['purchase', 'signup'])
->with('user.profile')
->groupBy('event_type')
->get();

// Relationships across custom tables
$products = Product::with('categories', 'reviews.user')
->whereHas('reviews', fn($q) => $q->where('rating', '>=', 4))
->orderBy('created_at', 'desc')
->paginate(20);
```

### Key Advantages
- **Consistent API** - Same syntax for all database operations
- **Custom Table Support** - WordPress has no native functions for custom tables
- **Modern Relationships** - Elegant handling of complex data relationships
- **Laravel Familiarity** - Developers can leverage existing Eloquent knowledge
- **Code Maintainability** - Clean, readable, and testable code

## 🛠️ Advanced Features

### Model Features
- **Active Record Pattern** - Intuitive object-based data manipulation
- **Mass Assignment Protection** - Security through fillable/guarded properties
- **Attribute Casting** - Automatic data type conversion
- **Mutators & Accessors** - Custom attribute handling
- **Model Events** - Hook into model lifecycle (creating, created, updating, etc.)
- **Soft Deletes** - Non-destructive record deletion
- **Timestamps** - Automatic created_at/updated_at management

### Query Builder Features
- **Fluent Interface** - Method chaining for readable queries
- **Advanced Where Clauses** - Complex filtering conditions
- **Joins** - Inner, left, right table joins
- **Aggregates** - Count, sum, average calculations
- **Raw Queries** - Direct SQL when needed
- **Query Scopes** - Reusable query filters

### Schema Management
- **Laravel-style Migrations** - Version-controlled database changes
- **Table Creation & Modification** - Complete DDL support
- **Index Management** - Performance optimization
- **Foreign Key Constraints** - Referential integrity

### Relationship Support
- **One-to-One** - Single related model
- **One-to-Many** - Collections of related models
- **Many-to-Many** - Complex relationship handling
- **Polymorphic Relationships** - Flexible associations

## 💡 Use Cases

### Perfect For
- **Admin Dashboards** - Fast backend data management
- **API Endpoints** - High-performance data serving
- **Analytics & Reporting** - Complex data analysis
- **Real-time Features** - Live data updates
- **Custom Applications** - Modern web app development on WordPress

### WordPress Integration Scenarios
- **Hybrid Approach** - ORM for admin, WordPress native for frontend
- **Performance Critical** - Replace slow WordPress queries
- **Complex Queries** - Advanced filtering and relationships
- **Custom Post Types** - Enhanced CPT management
- **User Management** - Extended user functionality

## 🔧 Configuration Options

### Custom Table Prefix
```php
define('WPORM_PREFIX', 'myapp_');
require_once 'path/to/wporm/bootstrap.php';
```

### Manual Initialization
```php
define('WPORM_NO_AUTO_INIT', true);
require_once 'path/to/wporm/bootstrap.php';

// Initialize manually when ready
\WordPressORM\ORM\ServiceProvider::boot();
```

### Development Mode
Enable detailed logging and debugging:
```php
define('WPORM_DEBUG', true);
```

## 📁 Project Structure

```
wporm/
├── bootstrap.php # Main bootstrap file
├── main.php # WordPress plugin entry point
├── src/ # Core ORM library
│ ├── Model.php # Base Eloquent-style model
│ ├── Builder.php # Fluent query builder
│ ├── Collection.php # Result collection
│ ├── WordPressModel.php # WordPress-specific base model
│ └── Schema/ # Database schema management
├── models/ # WordPress core models
│ ├── Post.php # WordPress posts/pages/CPTs
│ ├── User.php # WordPress users
│ ├── Comment.php # WordPress comments
│ └── ... # All WordPress core tables
├── docs/ # Comprehensive documentation
└── examples/ # Integration examples
```

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests if applicable
5. Commit your changes (`git commit -m 'Add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Submit a Pull Request

### Development Guidelines
- Follow PSR-4 autoloading standards
- Maintain WordPress compatibility
- Include PHPDoc comments
- Test with multiple WordPress versions
- Ensure backward compatibility

## 📝 License

This project is licensed under the GPL v2 or later - compatible with WordPress licensing requirements.

## 🆘 Support & Community

- **Documentation**: Comprehensive guides in `/docs` directory
- **Examples**: Live demos and code samples included
- **Issues**: Report bugs and request features via GitHub Issues
- **Community**: Join discussions about WordPress ORM development

## 🙏 Acknowledgments

- **Inspired by [Laravel's Eloquent ORM](https://laravel.com/docs/eloquent)** - Bringing modern ORM patterns to WordPress
- **Built for WordPress Ecosystem** - Full compatibility with WordPress standards
- **Community Driven** - Developed with WordPress developer feedback
- **Performance Focused** - Optimized for WordPress hosting environments

---

**WordPress ORM** - Bringing modern database interaction to WordPress development while maintaining the ecosystem compatibility that makes WordPress great. 🚀