laminas/laminas-cache-storage-adapter-ext-mongodb
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
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
],
],
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');
}
}
config/cache.php to define MongoDB-specific cache options.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;
}
}
// 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();
mongodb connection configuration.Metadata class to inspect cache item details, including the MongoDB _id.ExtMongoDbResourceManager can be customized for specific MongoDB resource management needs.ExtMongoDbOptions are correctly configured, especially for custom resource managers.Metadata class to add custom metadata fields.use Laminas\Cache\Storage\Adapter\ExtMongoDb\Metadata;
class CustomMetadata extends Metadata
{
public function __construct(array $metadata = [])
{
parent::__construct($metadata);
$this->customField = $metadata['customField'] ?? null;
}
}
How can I help you explore Laravel packages today?