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

Laminas Cache Storage Adapter Ext Mongodb Laravel Package

laminas/laminas-cache-storage-adapter-ext-mongodb

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

To integrate laminas/laminas-cache-storage-adapter-ext-mongodb into a Laravel project, start by installing the package:

composer require laminas/laminas-cache-storage-adapter-ext-mongodb

First Use Case: Basic Cache Configuration

Leverage Laravel's service container to bind the MongoDB cache adapter. Add this to your config/app.php under providers:

'providers' => [
    // ...
    Laminas\Cache\Storage\Adapter\ExtMongoDb::class,
],

Register the adapter in config/cache.php:

'mongodb' => [
    'driver' => 'mongodb',
    'connection' => 'mongodb',
    'options' => [
        'ttl' => 3600, // Default TTL in seconds
    ],
],

Initializing the Cache

In your service or controller, inject the cache via Laravel's dependency injection:

use Laminas\Cache\Storage\Adapter\ExtMongoDb;

class MyService
{
    public function __construct(
        protected ExtMongoDb $cache
    ) {}

    public function storeData()
    {
        $this->cache->setItem('key', 'value');
        $item = $this->cache->getItem('key');
    }
}

Implementation Patterns

Workflow: Cache Integration with Laravel

  1. Configuration: Use Laravel's config/cache.php to define MongoDB-specific cache options.
  2. Dependency Injection: Bind the adapter to Laravel's service container.
  3. Usage: Utilize the cache in services, controllers, or middleware.

Example: Cache Middleware

Create a middleware to cache API responses:

use Laminas\Cache\Storage\Adapter\ExtMongoDb;

class CacheResponseMiddleware
{
    public function __construct(
        protected ExtMongoDb $cache
    ) {}

    public function handle($request, Closure $next)
    {
        $cacheKey = 'api_response_' . $request->path();
        $response = $this->cache->getItem($cacheKey);

        if ($response) {
            return response($response['data'], $response['status']);
        }

        $response = $next($request);
        $this->cache->setItem($cacheKey, [
            'data' => $response->getContent(),
            'status' => $response->getStatusCode()
        ], 3600); // Cache for 1 hour

        return $response;
    }
}

Integration Tips

  • Tagging: Use tags to manage cache invalidation efficiently.
  • TTL: Set appropriate TTL (Time-To-Live) values based on data volatility.
  • Connection Management: Ensure your MongoDB connection is properly configured and managed.

Example: Cache with Tags

// Set item with tags
$this->cache->setItem('user_data', $userData, 3600, ['users', 'profile']);

// Clear items by tag
$this->cache->clearByTags(['users']);

// Clear all items
$this->cache->clear();

Gotchas and Tips

Pitfalls

  • Connection Issues: Ensure your MongoDB connection is stable and properly configured. Use Laravel's mongodb connection configuration.
  • Data Serialization: The adapter automatically serializes data, but ensure your data types are compatible with MongoDB's BSON format.
  • TTL Precision: MongoDB's TTL index might not be as precise as other cache backends. Monitor cache expiration behavior.

Debugging

  • Logs: Enable debug mode in Laravel to log cache operations.
  • Metadata: Use the Metadata class to inspect cache item details, including the MongoDB _id.

Configuration Quirks

  • Resource Manager: The ExtMongoDbResourceManager can be customized for specific MongoDB resource management needs.
  • Options: Ensure ExtMongoDbOptions are correctly configured, especially for custom resource managers.

Extension Points

  • Custom Metadata: Extend the Metadata class to add custom metadata fields.
  • Event Listeners: Use Laravel's event system to listen to cache operations and perform additional logic.

Example: Custom Metadata

use Laminas\Cache\Storage\Adapter\ExtMongoDb\Metadata;

class CustomMetadata extends Metadata
{
    public function __construct(array $metadata = [])
    {
        parent::__construct($metadata);
        $this->customField = $metadata['customField'] ?? null;
    }
}

Tips for Daily Use

  • Cache Invalidation: Always clear cache when data changes to avoid stale data.
  • Monitoring: Use MongoDB's profiling to monitor cache performance.
  • Testing: Write unit tests to ensure cache operations behave as expected in different scenarios.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky