snowbuilds/laravel-mirror

Laravel recommendation engine

0.0.3-alpha 2023-08-12 20:07 UTC

This package is auto-updated.

Last update: 2024-04-17 03:20:20 UTC


README

Laravel Mirror Package Logo

Latest Version on Packagist Total Downloads GitHub Actions

Introduction

Bring your user experience to the next level! Laravel Mirror lets you suggest content to your users intelligently! Easily recommend blog posts, products, recipes, books, etc., with pure PHP! Start by registering a recommendation strategy and routinely updating recommendations in a CRON job!

Installation

You can install the package via composer:

composer require "snowbuilds/laravel-mirror:^0.0.3-alpha"
php artisan vendor:publish --provider="SnowBuilds\Mirror\MirrorServiceProvider"

Usage

Registering a strategy is as simple as comparing two values! We added some utilities for convenience. For example, recommending blog posts with similar titles:

use SnowBuilds\Mirror\Concerns\Recommendations;
use SnowBuilds\Mirror\Mirror;

class Post extends Model
{
    use Recommendations;

    public function registerRecommendations(): void
    {
        $this->registerStrategy(Post::class)
            ->levenshtein('title');
    }
}

Weighted Averages

It is possible to combine algorithms! For example, suggesting posts with similar titles and tags. Adding weights will give fields precedence. Larger numbers have higher precedence. We made the title field score higher in a recommendation engine than the tags:

public function registerRecommendations(): void
{
    $this->registerStrategy(Post::class)
        ->levenshtein('title', 2)
        ->euclidean('tags', 1);
}

Different Properties in the Same Calculation

You can add a second parameter to the utility method when comparing properties with different names. For example, users should see posts based on their biography and followed communities:

class User extends Model
{
    use Recommendations;

    public function registerRecommendations(): void
    {
        $this->registerStrategy(Post::class)
            ->levenshtein('biography', 'title', 1) // compare biography to post title
            ->euclidean('communities', 'tags', 3); // compare communities to post tags
    }
}

Custom Scoring algorithms

When the helper utilities are insufficient, you can invoke custom algorithms using the using method. The first value, $a, is the model that has recommendations, and the second value, $b, is the model being suggested:

class User extends Model
{
    public function registerRecommendations(): void
    {
        $this->registerStrategy(Post::class)
            ->using(function (User $a, Post $b) {
                return Algorithm::levenshtein($a->name, $b->name);
            });
    }
}

Combining Weights with Custom Algorithms

Weights can also be applied to custom algorithms. The weights are applied in the order that the algorithm was registered. Our custom title comparator will take precedence over our tag comparator:

public function registerRecommendations(): void
{
    $this->registerStrategy(Post::class)
        ->using(function ($a, $b) {
            return Algorithm::levenshtein($a->title, $b->title);
        })
        ->using(function ($a, $b) {
            return Algorithm::euclidean($a->tags, $b->tags);
        })
        ->weights([2,1]);
}

Managing Multiple Algorithms and Weights

The code becomes hard to read when using multiple custom algorithms and weights. If you use an associative array, you can keep your algorithms and weights organized:

public function registerRecommendations(): void
{
    $this->registerStrategy(Post::class)
        ->using([
            'titles' => fn ($a, $b) => Algorithm::levenshtein($a->title, $b->title),
            'tags' => fn ($a, $b) => Algorithm::levenshtein($a->tags, $b->tags),
        ])
        ->weights([
            'titles' => 2,
            'tags' => 1,
        ]);
}

Macros - Extracting Algorithms

When your custom algorithm is too cumbersome, you can extract it into a macro. We use an internal utility for registering algorithms, which you are free to use in your macros. This will create a clean utility API ->huggingFace for our user model:

// ServiceProvider.php
ScoringStrategy::macro('huggingFace', function (...$args) {
  return $this->registerAlgorithm(
    fn($a, $b) => HuggingFace::invokeEmbedding($a, $b),
    ...$args
  );
});

// Model.php
class User extends Model 
{
    public function registerRecommendations(): void
    {
        $this->registerStrategy(User::class)
            ->euclidean('follewers')
            ->huggingFace('activity')
            ->levenshtein('bio');
    }
}

Relationships

You can define a relationship between the model and the suggested content using the morphsRecommendation method. The content is ordered by the most suggested content:

class User extends Authenticatable
{
    use Recommendations;

    public function recommendedRecipes() {
        return $this->morphRecommendation(Recipe::class);
    }
}

Generating Recommendation Matrix

Calculating recommendations is resource-intensive. Laravel Mirror provides a command for syncing recommendations. After syncing, the recommendations are stored in the database and you will be able to fetch related suggestions:

php artisan mirror:sync

In production, this should be a CRON job or registered in the Laravel kernel.

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command('mirror:sync')->daily();
    }
}

Roadmap

  • Blazingly Fast!
  • Polymorphic recommendations
  • Recommendation collections
  • Common comparison algorithms
  • Sync command
  • Testing
  • Programmatically invoke syncing actions
  • Simplified API for weights and faceted algorithms
  • Queueing
  • More algorithms
  • More settings

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security-related issues, please email dev@snowlaboratory.com instead of using the issue tracker.

Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Credits

License

The MIT License (MIT). Please see License File for more information.