PHPackages                             cmatosbc/mnemosyne - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. cmatosbc/mnemosyne

ActiveLibrary

cmatosbc/mnemosyne
==================

PSR compliant caching system using PHP attributes.

1.2.0(1y ago)44gpl-3.0-or-laterPHPPHP &gt;=8.0

Since Dec 11Pushed 1y ago1 watchersCompare

[ Source](https://github.com/cmatosbc/mnemosyne)[ Packagist](https://packagist.org/packages/cmatosbc/mnemosyne)[ RSS](/packages/cmatosbc-mnemosyne/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (4)Versions (7)Used By (0)

Mnemosyne - PHP Attribute-based Caching Library
===============================================

[](#mnemosyne---php-attribute-based-caching-library)

[![PHP Lint](https://github.com/cmatosbc/mnemosyne/actions/workflows/lint.yml/badge.svg)](https://github.com/cmatosbc/mnemosyne/actions/workflows/lint.yml) [![PHPUnit Tests](https://github.com/cmatosbc/mnemosyne/actions/workflows/phpunit.yml/badge.svg)](https://github.com/cmatosbc/mnemosyne/actions/workflows/phpunit.yml) [![PHP Composer](https://github.com/cmatosbc/mnemosyne/actions/workflows/composer.yml/badge.svg)](https://github.com/cmatosbc/mnemosyne/actions/workflows/composer.yml)

Mnemosyne is a powerful and flexible caching library for PHP 8.0+ that uses attributes to simplify cache management. It provides automatic caching and invalidation based on method attributes, making it easy to add caching to your application.

Features
--------

[](#features)

- Attribute-based caching configuration
- Automatic cache key generation
- Parameter-based cache keys with interpolation
- Automatic and manual cache invalidation
- Cache tags for group invalidation
- PSR-16 (SimpleCache) compatibility
- Flexible cache key templates
- Smart serialization handling:
    - Automatic serialization of complex objects
    - Optional raw storage for simple data types
    - Full control over serialization behavior

Installation
------------

[](#installation)

```
composer require cmatosbc/mnemosyne
```

Usage
-----

[](#usage)

To use Mnemosyne in your classes, you must:

1. Use the `CacheTrait` in your class
2. Inject a PSR-16 compatible cache implementation
3. Apply the `Cache` attribute to methods you want to cache

### Basic Usage

[](#basic-usage)

```
use Mnemosyne\Cache;
use Mnemosyne\CacheTrait;
use Psr\SimpleCache\CacheInterface;

class UserService
{
    use CacheTrait;  // Required to enable caching functionality

    public function __construct(CacheInterface $cache)
    {
        $this->cache = $cache;
    }

    #[Cache(ttl: 3600)]
    public function getUser(int $id): array
    {
        return $this->cacheCall('doGetUser', func_get_args());
    }

    private function doGetUser(int $id): array
    {
        // Expensive database query here
        return ['id' => $id, 'name' => 'John Doe'];
    }
}
```

### Serialization Control

[](#serialization-control)

The `Cache` attribute allows you to control how values are stored in cache:

```
class UserService
{
    use CacheTrait;

    // Automatically serialize complex objects
    #[Cache(key: 'user:{id}', ttl: 3600, serialize: true)]
    public function getUser(int $id): User
    {
        return $this->cacheCall('doGetUser', func_get_args());
    }

    // Store simple arrays without serialization
    #[Cache(key: 'users:list', ttl: 3600, serialize: false)]
    public function getUsersList(): array
    {
        return $this->cacheCall('doGetUsersList', func_get_args());
    }
}
```

### Custom Cache Keys

[](#custom-cache-keys)

```
class UserService
{
    use CacheTrait;

    #[Cache(key: 'user:{id}', ttl: 3600)]
    public function getUser(int $id): array
    {
        return $this->cacheCall('doGetUser', func_get_args());
    }

    #[Cache(key: 'users:dept:{deptId}:status:{status}', ttl: 3600)]
    public function getUsersByDepartment(int $deptId, string $status): array
    {
        return $this->cacheCall('doGetUsersByDepartment', func_get_args());
    }
}
```

### Cache Invalidation

[](#cache-invalidation)

#### Automatic Invalidation

[](#automatic-invalidation)

```
class UserService
{
    use CacheTrait;

    #[Cache(
        key: 'user:{id}',
        ttl: 3600
    )]
    public function getUser(int $id): array
    {
        return $this->cacheCall('doGetUser', func_get_args());
    }

    #[Cache(invalidates: ['user:{id}'])]
    public function updateUser(int $id, array $data): void
    {
        $this->cacheCall('doUpdateUser', func_get_args());
    }

    #[Cache(
        key: 'user:profile:{id}',
        ttl: 3600,
        invalidates: ['user:{id}', 'users:dept:{deptId}:status:active']
    )]
    public function updateProfile(int $id, int $deptId): array
    {
        return $this->cacheCall('doUpdateProfile', func_get_args());
    }
}
```

#### Manual Invalidation

[](#manual-invalidation)

```
class UserService
{
    use CacheTrait;

    public function forceRefresh(int $userId): void
    {
        $this->invalidateCache("user:$userId");
        // Or invalidate multiple keys:
        $this->invalidateCacheKeys([
            "user:$userId",
            "user:profile:$userId"
        ]);
    }
}
```

### Cache Tags

[](#cache-tags)

Cache tags allow you to group related cache entries and invalidate them together. This is useful for managing cache dependencies and bulk invalidation.

```
class UserService
{
    use CacheTrait;

    #[Cache(
        key: 'user:{id}',
        ttl: 3600,
        tags: ['user', 'user-{id}']
    )]
    public function getUser(int $id): array
    {
        return $this->cacheCall('doGetUser', func_get_args());
    }

    #[Cache(
        key: 'user:profile:{id}',
        ttl: 3600,
        tags: ['user', 'user-{id}']
    )]
    public function getUserProfile(int $id): array
    {
        return $this->cacheCall('doGetUserProfile', func_get_args());
    }

    public function updateUser(int $id): void
    {
        // Invalidate all caches for a specific user
        $this->invalidateTag("user-$id");
    }

    public function clearAllUserCaches(): void
    {
        // Invalidate all user-related caches
        $this->invalidateTag('user');
    }
}
```

Tags support parameter interpolation just like cache keys, allowing you to create dynamic tag names. When a tag is invalidated, all cache entries associated with that tag are automatically removed.

Best Practices
--------------

[](#best-practices)

1. Split cached methods into two parts:

    - A public method with the Cache attribute that handles caching
    - A private method with the actual implementation
2. Use meaningful cache keys that reflect the data structure
3. Set appropriate TTL values based on data volatility
4. Use cache invalidation when data is modified
5. Consider using cache tags for group invalidation

Testing
-------

[](#testing)

The library includes comprehensive PHPUnit tests. Run them with:

```
./vendor/bin/phpunit
```

License
-------

[](#license)

This project is licensed under the GNU General Public License v3.0 or later - see the LICENSE file for details. This means you are free to use, modify, and distribute this software, but any modifications must also be released under the GPL-3.0-or-later license.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance42

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

512d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3d97279f52b70d502ac21c0618e2822a0bae0523a7e69bb3fd33a592f21d5f06?d=identicon)[cmatosbc](/maintainers/cmatosbc)

---

Top Contributors

[![cmatosbc](https://avatars.githubusercontent.com/u/118901076?v=4)](https://github.com/cmatosbc "cmatosbc (11 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/cmatosbc-mnemosyne/health.svg)

```
[![Health](https://phpackages.com/badges/cmatosbc-mnemosyne/health.svg)](https://phpackages.com/packages/cmatosbc-mnemosyne)
```

###  Alternatives

[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[laminas/laminas-cache

Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

1076.9M130](/packages/laminas-laminas-cache)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[neos/flow

Flow Application Framework

862.0M449](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
