Repositories

Statamic uses a repository pattern to retrieve data from various places.

For example, when you call Entry::whereCollection('blog'), it asks “the entry repository” to get the blog entries instead of immediately assuming the entries will be located in a blog directory on the filesystem.

Out of the box, Statamic will typically use an implementation that gets data from the “Stache”, which is our file-backed database.

Custom Repositories

Let’s say you want to store your entries in a database. You would need to swap the default entry repository (which gets entries from the Stache) with your own that would get entries from a database.

In a service provider, you can re-bind the contract:

<?php

namespace App\Providers;

use App\DatabaseEntryRepository;
use Illuminate\Support\ServiceProvider;
use Statamic\Contracts\Entries\EntryRepository;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(
            EntryRepository::class,
            DatabaseEntryRepository::class
        );
    }
}

If you only need to customize small parts, feel free to have your repository class extend Statamic’s default ones. For example:

use Statamic\Stache\Repositories\EntryRepository;

class MyEntryRepository extends EntryRepository
{
    //
}

Custom Data Classes

Each repository is also responsible for making instances of their items. eg. an EntryRepository makes Entry classes. The make method will resolve the appropriate class out of the container based on the contract.

The repository has a bindings method that defines these. Your custom repository may override these to return different classes.

public static function bindings(): array
{
    return [
        Statamic\Contracts\Entries\Entry::class => DatabaseEntry::class,
    ];
}

Alternatively, if you want to use a custom item class without customizing the entire repository, you’re free to just re-bind that class in your service provider. This could be more useful to you if you just need to customize a method or two.

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(
            Statamic\Contracts\Entries\Entry::class,
            CustomEntry::class
        );
    }
}
Betterify this page on Github!