PHP code example of joshembling / cache-machine

1. Go to this page and download the library: Download joshembling/cache-machine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joshembling / cache-machine example snippets


use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    // ...
}

use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    /**
     * @var array<string, callable>
     */
    public static function cacheKeys(): array
    {
        $keys = [
            // Cache all posts with the eloquent query as the callback
            'all_posts' => fn () => self::all(),
        ];

        return $keys;
    }

    // ...
}

use JoshEmbling\CacheMachine\CacheMachine;

class Post extends Model
{
    use CacheMachine;

    const ALL = 'all_posts';
    const SELECT = 'select_posts';

    /**
     * @var array<string, callable>
     */
    public static function cacheKeys(): array
    {
        $keys = [
             // Cache all posts
            self::ALL => fn () => self::all(),

             // Cache all posts in a key => value format
            self::SELECT => fn () => self::get()->mapWithKeys(
                fn ($type) => [
                    $type->id => $type->title,
                ]
            ),
        ];

        return $keys;
    }

    // ...
}

// You may pass a string to the withdraw method.
Post::withdraw('all_posts');

// Or one of your model's static properties, relating to a key defined in the `cacheKeys()` method.
Post::withdraw(Post::ALL);

Post::forceFetch(Post::ALL)

// Fetch all posts to display on an archive
Post::withdraw('all_posts');

// Display a single blog article
Post::withdraw('all_posts')
    ->firstWhere('id', 2);

// Filter a user search query
Post::withdraw('all_posts')
    ->where('title', 'like', '%Laravel%')
    ->orWhere('published_at', '>', now()->subDays(30))
    ->map(fn ($post) => strtoupper($post->title))
    ->sortDesc();