How to access Laravel Capsule through the WordPress codebase?

Learn how to create instance of Laravel's Capsule in WordPress module and use it through the code.

Before you start, I insist you to check out the approach that is used for managing modules created in WordPress aplications here to fully understand this code. For more information about the reasons for using Capsule object, check out this thread.

Initialization

Create a database module in the FM\Core namespace and initialize it in the app facade. You can use lazy evaluation (call-by-need) as follows to create instance of Capsule only when needed. That's really useful method to not blocking thread when not needed.

namespace FM\Core;

use Illuminate\Database\Capsule\Manager as Capsule;

class Database
{
  private ?Capsule $capsule = null;

  public function capsule(): Capsule
  {
    if (is_null($this->capsule))  {
      global $wpdb;

      $this->capsule = new Capsule();
      $this->capsule->addConnection([
        'driver'    => 'mysql',
        'host'      => DB_HOST,
        'database'  => DB_NAME,
        'username'  => DB_USER,
        'password'  => DB_PASSWORD,
        'charset'   => DB_CHARSET,
        'collation' => $wpdb->collate,
        'prefix'    => $wpdb->prefix,
      ]);
      $this->capsule->setAsGlobal();
    }

    return $this->capsule;
  }
}

Usage

Now, you can use Capsule object in every place you need 🤓

fm()->database()->capsule()->table('users')->get();

Feedback

How satisfied you are after reading this article?