PHP code example of directorytree / activeredis

1. Go to this page and download the library: Download directorytree/activeredis 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/ */

    

directorytree / activeredis example snippets


namespace App\Redis;

use DirectoryTree\ActiveRedis\Model;

class Visit extends Model {}

use App\Redis\Visit;

$visit = Visit::create([
    'ip' => request()->ip(),
    'url' => request()->url(),
    'user_agent' => request()->userAgent(),
]);

$visit->ip; // xxx.xxx.xxx.xxx
$visit->url; // https://example.com
$visit->user_agent; // Mozilla/5.0 ...

$visit->id; // "f195637b-7d48-43ab-abab-86e93dfc9410"
$visit->getKey(); // "f195637b-7d48-43ab-abab-86e93dfc9410"
$visit->getHashKey(); // "visits:id:f195637b-7d48-43ab-abab-86e93dfc9410"

$visit->getKeyName(); // "id"
$visit->getBaseHash(); // "visits:id"
$visit->getHashPrefix(): // "visits"

$visit = Visit::create([
    'id' => 'custom-id',
    // ...
]);

$visit->id; // "custom-id"
$visit->getHashKey(); // "visits:id:custom-id"

Visit::create(['id' => 'custom-id']);

// DuplicateKeyException: A model with the key 'custom-id' already exists.
Visit::create(['id' => 'custom-id']);

// InvalidKeyException: A key is 

Visit::create(['id' => 'custom-id']);

// The existing model will be deleted.
Visit::create(['id' => 'custom-id'], force: true);

(new Visit(['id' => 'custom-id'])->save();

(new Visit(['id' => 'custom-id']))->save(force: true);

namespace App\Redis;

use DirectoryTree\ActiveRedis\Model;

class Visit extends Model
{
    /**
     * The key name for the model.
     */
    protected string $key = 'custom_key';
}

namespace App\Redis;

use Illuminate\Support\Str;
use DirectoryTree\ActiveRedis\Model;

class Visit extends Model
{    
    /**
     * Generate a new key for the model.
     */
    protected function getNewKey(): string
    {
        return Str::uuid();
    }
}

$visit->created_at; // \Carbon\Carbon('2024-01-01 00:00:00')
$visit->updated_at; // \Carbon\Carbon('2024-01-01 00:00:00')

$visit->touch();

$visit->touch('created_at');

class Visit extends Model
{
    /**
     * Indicates if the model should be timestamped.
     */
    public bool $timestamps = false;
}

class Visit extends Model
{
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'updated_date';
}

class Visit extends Model
{
    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = [
        'user_id' => 'integer',
        'authenticated' => 'boolean',
    ];
}

$visit = new Visit([
    'user_id' => '1',
    'authenticated' => '1',
    // ...
]);

$visit->user_id; // (int) 1
$visit->authenticated; // (bool) true

$visit->getAttributes(); // ['user_id' => '1', 'authenticated' => '1'],

use App\Enums\VisitType;

class Visit extends Model
{
    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = [
        'type' => VisitType::class,
    ];
}

$visit = Visit::create(['type' => VisitType::Unique]);
// Or:
$visit = Visit::create(['type' => 'unique']);

$visit->type; // (enum) VisitType::Unique

class Visit extends Model
{
    /**
     * The "booted" method of the model.
     */
    protected static function booted(): void
    {
        static::creating(function (Visit $visit) {
            // ...
        });
        
        // ...
    }
}

class VisitObserver
{
    /**
     * Handle the "creating" event.
     */
    public function creating(Visit $visit): void
    {
        // ...
    }
}

use App\Redis\Visit;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Visit::observe(VisitObserver::class);
    }
}

return [
    // ...
    
    'redis' => [
        'activeredis' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => '10',
        ],
    ],
];

class Visit extends Model
{
    /**
     * The Redis connection to use.
     */
    protected ?string $connection = 'activeredis';
}

$visit->update([
    'ip' => 'xxx.xxx.xxx.xxx',
    'url' => 'https://example.com',
    'user_agent' => 'Mozilla/5.0 ...',
]);

$visit->ip = 'xxx.xxx.xxx.xxx';

$visit->save();

$visit->delete();

$deleted = Visit::destroy('f195637b-7d48-43ab-abab-86e93dfc9410');

echo $deleted; // 1

$deleted = Visit::destroy(['f195637b...', 'a195637b...']);

echo $deleted; // 2

$visit->setExpiry(now()->addMinutes(5));

$visit->getExpiry(); // \Carbon\Carbon|null

$visits = Visit::query()->get();

$visits = Visit::get();

$visit = Visit::find('f195637b-7d48-43ab-abab-86e93dfc9410');

Visit::findOrFail('missing'); // ModelNotFoundException

use App\Redis\Visit;
use Illuminate\Support\Collection;

Visit::chunk(100, function (Collection $visits) {
    $visits->each(function ($visit) {
        // ...
    });
});

use App\Redis\Visit;

Visit::each(function (Visit $visit) {
    // ...
}, 100);

use App\Redis\Visit;

Visit::each(function (Visit $visit) {
    if ($visit->ip === 'xxx.xxx.xxx.xxx') {
        return false;
    }
});

namespace App\Redis;

class Visit extends Model
{
    /**
     * The attributes that are searchable.
     */
    protected array $searchable = ['ip'];
}

class Visit extends Model
{
    /**
     * The attributes that are searchable.
     */
    protected array $searchable = ['user_id', 'ip'];
}

$visit = UserVisit::create([
    'user_id' => 1,
    'ip' => request()->ip(),
]);

$visit->getHashKey(); // "user_visits:id:f195637b-7d48-43ab-abab-86e93dfc9410:ip:127.0.0.1:user_id:1"

// SCAN ... MATCH visits:id:*:ip:127.0.0.1:user_id:1
$visits = Visit::query()
    ->where('user_id', 1)
    ->where('ip', '127.0.0.1')
    ->get();

// SCAN ... MATCH visits:id:*:ip:127.0.0.1:user_id:*
$visit = Visit::where('ip', '127.0.0.1')->first();

// SCAN ... MATCH visits:id:*:ip:127.0.*:user_id:*
$visit = Visit::where('ip', '127.0.*')->first();

// SCAN ... MATCH visits:id:*:ip:null:user_id:*
$visit = Visit::where('ip', 'null')->first();

$visit = Visit::create(['user_id' => 1]);

// HDEL visits:id:f195637b-7d48-43ab-abab-86e93dfc9410:ip:127.0.0.1:user_id:1
// HSET visits:id:f195637b-7d48-43ab-abab-86e93dfc9410:ip:127.0.0.1:user_id:2
$visit->update(['user_id' => 2]);

use DirectoryTree\ActiveRedis\Model;

// Pest
beforeAll(function () {
    Model::setRepository('array');
});

// PHPUnit
protected function setUp(): void
{
    parent::setUp();

    Model::setRepository('array');
}

use Illuminate\Support\Facades\Redis;

// Pest
beforeEach(function () {
    Redis::flushdb();
});

// PHPUnit
protected function setUp(): void
{
    parent::setUp();

    Redis::flushdb();
}