friendsofcat/laravel-couchbase

A Couchbase based Eloquent model and Query builder for Laravel

2.1.0 2023-05-17 16:55 UTC

README

An Eloquent model and Query builder with support for Couchbase, using the original Laravel API. This library extends the original Laravel classes, so it uses exactly the same methods.

Credits

Table of contents

Installation

Couchbase compatibility

Make sure you have the Couchbase PHP driver installed. You can find installation instructions at http://developer.couchbase.com/documentation/server/current/sdk/php/start-using-sdk.html

Installation using composer:

composer require friendsofcat/laravel-couchbase

And add the service provider in config/app.php:

FriendsOfCat\Couchbase\CouchbaseServiceProvider::class,

For usage with Lumen, add the service provider in bootstrap/app.php. In this file, you will also need to enable Eloquent. You must however ensure that your call to $app->withEloquent(); is below where you have registered the CouchbaseServiceProvider :

$app->register(FriendsOfCat\Couchbase\CouchbaseServiceProvider::class);

$app->withEloquent();

The service provider will register a couchbase database extension with the original database manager. There is no need to register additional facades or objects. When using couchbase connections, Laravel will automatically provide you with the corresponding couchbase objects.

For usage outside Laravel, check out the Capsule manager and add:

$capsule->getDatabaseManager()->extend('couchbase', function($config) {
    return new FriendsOfCat\Couchbase\Connection($config);
});

Usage

composer require friendsofcat/laravel-couchbase
  • And add a new couchbase connection:
'couchbase' => [
    'driver'   => 'couchbase',
    'host'     => env('DB_HOST', 'localhost'),
    'port'     => env('DB_PORT', 8091),
    'bucket'   => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
],
  • You can connect to multiple servers or replica sets with the following configuration:
'couchbase' => [
    'driver'   => 'couchbase',
    'host'     => ['host1', 'host2'],
    'port'     => env('DB_PORT', 8091),
    'bucket'   => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
],
  • Model usage
<?php

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {
  $connection = 'couchbase';
}

More on that on eloquent section below

Commands

couchbase couchbase:bucket:create Create a bucket. couchbase:bucket:create-primary-index Create index on bucket to allow performing nql queries couchbase:bucket:delete Delete a bucket. couchbase:bucket:flush Remove all data on bucket (clear database). couchbase:bucket:list List available buckets on cluster couchbase:cluster:init Initialize couchbase cluster before usage

Before usage in Laravel

Note that all the following commands can be done on the browser at localhost:8091

  • Init cluster before any usage
php artisan couchbase:cluster:init
  • Create a bucket
php artisan couchbase:bucket:create --bucket canvas

Eloquent

This package includes a Couchbase enabled Eloquent class that you can use to define Models for corresponding collections.

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {}

As Couchbase does not provide the concept of tables, documents will instead be defined by a property called _type. Like the original Eloquent, the lower-casem plural name of the class will be used as the "table" name and will be placed inside the _type property of each document.

You may specify a custom type (alias for table) by defining a table property on your model:

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $table = 'my_users';

}

NOTE: Eloquent will also assume that each collection has a primary key column named _id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class MyModel extends Eloquent {

    protected $connection = 'couchbase';

}

Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent

Optional: Alias

You may also register an alias for the Couchbase model by adding the following to the alias array in config/app.php:

'CouchbaseModel'       => 'FriendsOfCat\Couchbase\Eloquent\Model',

This will allow you to use the registered alias like:

class MyModel extends CouchbaseModel {}

Query Builder

The database driver plugs right into the original query builder. When using couchbase connections, you will be able to build fluent queries to perform database operations.

$users = DB::table('users')->get();

$user = DB::table('users')->where('name', 'John')->first();

If you did not change your default database connection, you will need to specify it when querying.

$user = DB::connection('couchbase')->table('users')->get();

Read more about the query builder on http://laravel.com/docs/queries

Schema

As this Couchbase driver implementation uses a single bucket for all documents, a Schema builder is not implemented.

Examples

Basic Usage

Retrieving All Models

$users = User::all();

Retrieving A Record By Primary Key

$user = User::find('517c43667db388101e00000f');

Wheres

$users = User::where('votes', '>', 100)->take(10)->get();

Or Statements

$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();

And Statements

$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();

Using Where In With An Array

$users = User::whereIn('age', [16, 18, 20])->get();

Using Where Between

$users = User::whereBetween('votes', [1, 100])->get();

Where null

$users = User::whereNull('updated_at')->get();

Where is missing

$users = User::whereIsMissing('updated_at')->get();

Where is valued

$users = User::whereIsValued('updated_at')->get();

Order By

$users = User::orderBy('name', 'desc')->get();

Offset & Limit

$users = User::skip(10)->take(5)->get();

Distinct

Distinct requires a field for which to return the distinct values.

$users = User::distinct()->get(['name']);
// or
$users = User::distinct('name')->get();

Distinct can be combined with where:

$users = User::where('active', true)->distinct('name')->get();

Advanced Wheres

$users = User::where('name', '=', 'John')->orWhere(function($query)
    {
        $query->where('votes', '>', 100)
              ->where('title', '!=', 'Admin');
    })
    ->get();

Group By

Selected columns that are not grouped will be aggregated with the $last function.

$users = Users::groupBy('title')->get(['title', 'name']);

Aggregation

$total = Order::count();
$price = Order::max('price');
$price = Order::min('price');
$price = Order::avg('price');
$total = Order::sum('price');

Aggregations can be combined with where:

$sold = Orders::where('sold', true)->sum('price');

Like

$user = Comment::where('body', 'like', '%spam%')->get();

NOTE: Like checks in Couchbase are case sensitive

Incrementing or decrementing a value of a column

Perform increments or decrements (default 1) on specified attributes:

User::where('name', 'John Doe')->increment('age');
User::where('name', 'Jaques')->decrement('weight', 50);

The number of updated objects is returned:

$count = User->increment('age');

You may also specify additional columns to update:

User::where('age', '29')->increment('age', 1, ['group' => 'thirty something']);
User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']);

Soft deleting

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:

use FriendsOfCat\Couchbase\Eloquent\SoftDeletes;

class User extends Eloquent {

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

For more information check http://laravel.com/docs/eloquent#soft-deleting

Inserts, updates and deletes

Inserting, updating and deleting records works just like the original Eloquent.

Saving a new model

$user = new User;
$user->name = 'John';
$user->save();

You may also use the create method to save a new model in a single line:

User::create(['name' => 'John']);

Updating a model

To update a model, you may retrieve it, change an attribute, and use the save method.

$user = User::first();
$user->email = 'john@foo.com';
$user->save();

Deleting a model

To delete a model, simply call the delete method on the instance:

$user = User::first();
$user->delete();

Or deleting a model by its key:

User::destroy('517c43667db388101e00000f');

For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete

Relations

Supported relations are:

  • hasOne
  • hasMany
  • belongsTo
  • belongsToMany
  • embedsOne
  • embedsMany

Example:

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function items()
    {
        return $this->hasMany('Item');
    }

}

And the inverse relation:

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class Item extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}

The belongsToMany relation will not use a pivot "table", but will push id's to a related_ids attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to null:

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function groups()
    {
        return $this->belongsToMany('Group', null, 'user_ids', 'group_ids');
    }

}

Other relations are not yet supported, but may be added in the future. Read more about these relations on http://laravel.com/docs/eloquent#relationships

EmbedsMany Relations

If you want to embed Models, rather than referencing them, you can use the embedsMany relation. This relation is similar to the hasMany relation, but embeds the Models inside the parent object.

REMEMBER: these relations return Eloquent collections, they don't return query builder objects!

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class User extends Eloquent {

    public function books()
    {
        return $this->embedsMany('Book');
    }

}

You access the embedded Models through the dynamic property:

$books = User::first()->books;

The inverse relation is automagically available, you don't need to define this reverse relation.

$user = $book->user;

Inserting and updating embedded Models works similar to the hasMany relation:

$book = new Book(['title' => 'A Game of Thrones']);

$user = User::first();

$book = $user->books()->save($book);
// or
$book = $user->books()->create(['title' => 'A Game of Thrones'])

You can update embedded Models using their save method:

$book = $user->books()->first();

$book->title = 'A Game of Thrones';

$book->save();

You can remove an embedded model by using the destroy method on the relation, or the delete method on the model:

$book = $user->books()->first();

$book->delete();
// or
$user->books()->destroy($book);

If you want to add or remove an embedded model, without touching the database, you can use the associate and dissociate methods. To eventually write the changes to the database, save the parent object:

$user->books()->associate($book);

$user->save();

Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method:

return $this->embedsMany('Book', 'local_key');

Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections

EmbedsOne Relations

The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model.

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class Book extends Eloquent {

    public function author()
    {
        return $this->embedsOne('Author');
    }

}

You access the embedded Models through the dynamic property:

$author = Book::first()->author;

Inserting and updating embedded Models works similar to the hasOne relation:

$author = new Author(['name' => 'John Doe']);

$book = Books::first();

$author = $book->author()->save($author);
// or
$author = $book->author()->create(['name' => 'John Doe']);

You can update the embedded model using the save method:

$author = $book->author;

$author->name = 'Jane Doe';
$author->save();

You can replace the embedded model with a new model like this:

$newAuthor = new Author(['name' => 'Jane Doe']);
$book->author()->save($newAuthor);

MySQL Relations

If you're using a hybrid Couchbase and SQL setup, you're in luck! The model will automatically return a Couchbase- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-Models will need use the FriendsOfCat\Couchbase\Eloquent\HybridRelations trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations.

Example SQL-based User model:

use FriendsOfCat\Couchbase\Eloquent\HybridRelations;

class User extends Eloquent {

    use HybridRelations;

    protected $connection = 'mysql';

    public function messages()
    {
        return $this->hasMany('Message');
    }

}

And the Couchbase-based Message model:

use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent;

class Message extends Eloquent {

    protected $connection = 'couchbase';

    public function user()
    {
        return $this->belongsTo('User');
    }

}

Query Caching

You may easily cache the results of a query using the remember method:

$users = User::remember(10)->get();

From: http://laravel.com/docs/queries#caching-queries

Query Logging

By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the disableQueryLog method:

DB::connection()->disableQueryLog();

From: http://laravel.com/docs/database#query-logging

Testing

  • Create bucket
  • Create bucket primary index
  • Run tests
  • Use RefreshDatabase trait to clear database between tests

TODO

This is not a fully featured eloquent driver. There are still some areas where attention would be needed. Just to name few:

  • Implement table concept using collection/scope instead of type. This could improve performance
  • Test commands
  • Test pagination
  • Helper uniqueId
  • custom RefreshDatabase trait to recreate bucket
  • add LazilyRefreshDatabase instead of RefreshDatabase Lead
// RefreshDatabase
$this->artisan(BucketDelete::class);
$this->artisan(BucketCreate::class);
$this->artisan(BucketCreatePrimaryIndex::class);
// check hook afterApplicationCreated, beforeApplicationDestroyed