Since I released the wp-eloquent package, there were some questions on how to use that actually? If someone is new to composer or a beginner in PHP, that might be a valid question and it’s okay to be. Composer is less used in the WordPress world. I was asked this question a few times till now, so I thought to write an article to clear up the confusions for the beginners.
Step 1: Create a new plugin
Let’s start by creating the most basic plugin:
<?php /** * Plugin Name: Test WP Eloquent * Description: This is a test Eloquent plugin * Plugin URI: https://tareq.co * Author: Tareq Hasan * Author URI: https://tareq.co * Version: 1.0 */ // don't call the file directly if ( !defined( 'ABSPATH' ) ) exit;
Step 2: Install the dependencies
Now enter to the plugin folder in your terminal and run this command:
cd /path/to/plugin/test-eloquent composer require tareq1988/wp-eloquent:dev-master
Of course, you must have composer installed, then you should see a bunch of things happening in the terminal:
What composer does is, it grabs all the dependencies the wp-eloquent package requires, such as the main Eloquent package, Doctrine, Carbon and others. You don’t have to worry about missing any package.
Step 3: Include the autoloader
The beauty of composer is autoloading, so you don’t have to know how and which files you need to add in your plugin to call something. You just need to include one file to your plugin and everything will just work. Composer will load those classes or functions for you automatically. So now in your main plugin file, include the autoloader file.
require_once __DIR__ . '/vendor/autoload.php';
Now you have the wp-eloquent package installed in your plugin and you can take the advantage of the Eloquent ORM. Please refer to the github repository of the package and there are a bunch of examples there to get you started. Here’s the plugin looks like now:
<?php /** * Plugin Name: Test WP Eloquent * Description: This is a test Eloquent plugin * Plugin URI: https://tareq.co * Author: Tareq Hasan * Author URI: https://tareq.co * Version: 1.0 */ // don't call the file directly if ( !defined( 'ABSPATH' ) ) exit; require_once __DIR__ . '/vendor/autoload.php'; add_action( 'init', function() { $db = \WeDevs\ORM\Eloquent\Database::instance(); var_dump( $db->table('users')->find(1) ); var_dump( $db->select('SELECT * FROM wp_users WHERE id = ?', [1]) ); var_dump( $db->table('users')->where('user_login', 'admin')->first() ); } );
Enjoy!
Thank you Tareq for providing this tutorial. Exactly what I was looking for.
This is very nice but why do we need to use wp-eloquent while we can perform this kind of db actions using $wpdb object? What is the benefit of using wp-eloquent?
Thanks
Eloquent is an ORM. You’ve to know why you need to use an ORM in the first place.
OK! I understand. Thanks for your reply 🙂