Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Keyval Db Laravel Package

dovstone/keyval-db

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require dovstone/keyval-db
    

    Ensure your composer.json specifies Laravel compatibility (e.g., "require": {"laravel/framework": "^10.0"}).

  2. Publish Configuration (if applicable):

    php artisan vendor:publish --provider="Dovstone\KeyvalDb\KeyvalDbServiceProvider"
    

    Note: Verify if the package publishes config via config/keyval-db.php or similar.

  3. Database Setup:

    • Run migrations (if the package includes them):
      php artisan migrate
      
    • Alternatively, manually create a table (e.g., keyval_entries) with columns like key (string), value (text/json), and expires_at (timestamp).
  4. First Usage:

    use Dovstone\KeyvalDb\Facades\KeyvalDb;
    
    // Set a key-value pair
    KeyvalDb::set('user:123:preferences', ['theme' => 'dark']);
    
    // Get a value
    $preferences = KeyvalDb::get('user:123:preferences');
    
    // Delete a key
    KeyvalDb::delete('user:123:preferences');
    
  5. Check Documentation:

    • Inspect the package’s src/ directory for classes like KeyvalDbManager, KeyvalDbQueryBuilder, or KeyvalDbModel.
    • Look for a README.md or USAGE.md in the repo (even if minimal).

Implementation Patterns

Core Workflows

1. Key-Value Operations

  • Basic CRUD:
    // Set with TTL (time-to-live in seconds)
    KeyvalDb::set('cache:homepage', $data, 3600);
    
    // Get with fallback
    $data = KeyvalDb::get('cache:homepage', []);
    
    // Check existence
    if (KeyvalDb::has('cache:homepage')) { ... }
    
    // Delete
    KeyvalDb::delete('cache:homepage');
    
  • Batch Operations:
    KeyvalDb::setMultiple([
        'key1' => 'value1',
        'key2' => 'value2',
    ]);
    
    $batch = KeyvalDb::getMultiple(['key1', 'key2']);
    

2. Query Builder Integration

  • If the package supports query building (e.g., for searching keys):
    // Example: Find keys matching a pattern
    $results = KeyvalDb::query()
        ->where('key', 'like', 'user:%')
        ->get();
    
  • Assumption: The package may extend Laravel’s Builder or use raw queries. Verify via source code.

3. Event-Driven Extensions

  • Listen for key changes (if supported):
    use Dovstone\KeyvalDb\Events\KeyUpdated;
    
    event(new KeyUpdated('user:123:preferences'));
    
  • Register listeners in EventServiceProvider:
    protected $listen = [
        KeyUpdated::class => [
            \App\Listeners\SyncUserPreferences::class,
        ],
    ];
    

4. Integration with Eloquent

  • Hybrid Models: Attach key-value behavior to Eloquent models:
    use Dovstone\KeyvalDb\Traits\HasKeyval;
    
    class User extends Model
    {
        use HasKeyval;
    
        protected $keyvalTable = 'user_metadata';
    }
    
    // Usage:
    $user->setKeyval('preferences', ['theme' => 'dark']);
    $prefs = $user->getKeyval('preferences');
    

5. Caching Layer

  • Use keyval-db as a persistent cache backend (replace Redis/Memcached for small projects):
    // Cache a value for 1 hour
    KeyvalDb::set('cache:featured_posts', $posts, 3600);
    
    // Retrieve cached data
    $posts = KeyvalDb::get('cache:featured_posts', function () {
        return Post::featured()->get();
    });
    

Integration Tips

1. Service Provider Binding

  • Bind the package to the container for dependency injection:
    $this->app->singleton('keyval', function ($app) {
        return new \Dovstone\KeyvalDb\KeyvalDbManager();
    });
    
  • Resolve in controllers:
    public function __construct(private KeyvalDbManager $keyval) {}
    

2. Middleware for Keyval Protection

  • Restrict access to sensitive keys:
    public function handle($request, Closure $next)
    {
        if ($request->keyvalKey && !str_starts_with($request->keyvalKey, 'safe:')) {
            abort(403);
        }
        return $next($request);
    }
    

3. Testing

  • Use Laravel’s testing helpers:
    public function test_keyval_operations()
    {
        $this->artisan('migrate:fresh')
             ->assertExitCode(0);
    
        KeyvalDb::set('test:key', 'value');
        $this->assertEquals('value', KeyvalDb::get('test:key'));
    }
    
  • Mock the package in unit tests:
    $mock = Mockery::mock('alias:keyval');
    $mock->shouldReceive('get')->andReturn(['data']);
    

4. Performance Optimization

  • Indexing: Ensure the key column is indexed in the database:
    Schema::table('keyval_entries', function (Blueprint $table) {
        $table->index('key');
    });
    
  • Batch Writes: For bulk operations, use transactions:
    DB::transaction(function () {
        KeyvalDb::setMultiple($largeDataset);
    });
    

5. API Endpoints

  • Expose keyval operations via API:
    Route::get('/api/keyval/{key}', function ($key) {
        return KeyvalDb::get($key);
    });
    
    Route::post('/api/keyval', function (Request $request) {
        KeyvalDb::set($request->key, $request->value);
        return response()->json(['status' => 'set']);
    });
    

Gotchas and Tips

Pitfalls

  1. No Official Documentation:

    • The package lacks a README.md or usage guide. Reverse-engineer usage by inspecting:
      • src/ directory for classes/methods.
      • tests/ for example usage.
      • composer.json for dependencies (e.g., Laravel version requirements).
  2. Undocumented Dependencies:

    • Check for hidden dependencies (e.g., doctrine/dbal, illuminate/database) that may conflict with your project.
    • Run composer why-not vendor/package to debug missing dependencies.
  3. Database Schema Assumptions:

    • The package may assume a specific table structure (e.g., keyval_entries). Verify migrations or create your own if needed:
      Schema::create('keyval_entries', function (Blueprint $table) {
          $table->string('key')->unique();
          $table->text('value');
          $table->timestamp('expires_at')->nullable();
          $table->timestamps();
      });
      
  4. Namespace Collisions:

    • If the package uses KeyvalDb or similar, alias it to avoid conflicts:
      use Dovstone\KeyvalDb\Facades\KeyvalDb as Keyval;
      
  5. No Built-in Serialization:

    • The package may not handle serialization/deserialization of complex values (e.g., objects, arrays). Manually serialize if needed:
      KeyvalDb::set('user:123:data', serialize($complexObject));
      $object = unserialize(KeyvalDb::get('user:123:data'));
      
    • Alternative: Use json_encode()/json_decode() for JSON-compatible data.
  6. Lack of Query Builder Features:

    • The package may not support advanced queries (e.g., where('value', 'like', '%search%')). Fallback to raw queries:
      $results = DB::table('keyval_entries')
          ->where('value', 'like', '%search%')
          ->get();
      
  7. No Rate Limiting:

    • Keyval operations may not be rate-limited. Add middleware for public APIs:
      Route::middleware(['throttle:60,1'])->group(function () {
          // Keyval API routes
      });
      
  8. TTL (Time-to-Live) Quirks:

    • Expiring keys may not trigger events or cleanup. Schedule a cron job to prune expired keys:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver