If you are a plugin writer like me and you write random WordPress plugins for various purposes, chances are you have to write many SQL queries for many cases. But if you look into modern PHP frameworks like Laravel, Symfony, Zend and every other frameworks, you will see they don’t write much raw SQL queries by hand. Instead, everyone is using ORM. In few cases you might have to write raw SQL queries, with ORM you can do that as well.
If you look at the WordPress world, we are still stuck with the WPDB global object. It’s an Active Record class, but can’t be called an ORM. The main reason I like ORM is it reduces so much codes and facilitates many magical features without writing raw queries, instead of manipulate them using an Object Oriented like language. Also you can use many adapters for many databases (though it’s not possible right now in WordPress).
If you are writing a large plugin which involves many custom database tables, chances are you will get lost among those tables and queries very shortly. It happened to me as well and I was looking for using ORM’s in WordPress. But there aren’t so many good tools for that. So I looked into Laravel as it’s huge popular now a days. Laravel uses a package named Eloquent as its ORM provider. As it’s a composer package, you can easily use Eloquent into any PHP application.
There are ways to use Eloquent independently, but it requires you to create a separate connection to database. But as WordPress is already connected to the database, why create a new connection? And if we use Eloquent like that, we will miss database reporting from various debugging plugins like debug-bar, query-monitor, etc.
That’s why I wrote a composer package to use Eloquent ORM inside WordPress using the same database connection using WPDB. The benefits are:
- Eloquent is mainly used here as the query builder
- WPDB is used to run queries built by Eloquent
- It doesn’t create any extra MySQL connection
- You get to use the WordPress debug tools/plugins
The package is not perfect, but please do checkout the Github repository for detailed information and usage instruction. Pull requests are always welcome.