Configuration and hooks | laravel-responsecache-rust | Spatie       

 SPATIE  

laravel-responsecache-rust
==========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-responsecache-rust](https://spatie.be/docs/laravel-responsecache-rust/v1)  Configuration and hooks

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-responsecache-rust/v1) 

  Configuration and hooks    
- [ Introduction ](https://spatie.be/docs/laravel-responsecache-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-responsecache-rust/v1/support-us)
- [ Installation ](https://spatie.be/docs/laravel-responsecache-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-responsecache-rust/v1/usage)
- [ Configuration and hooks ](https://spatie.be/docs/laravel-responsecache-rust/v1/configuration-and-hooks)
- [ Testing ](https://spatie.be/docs/laravel-responsecache-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-responsecache-rust/v1/changelog)

 Configuration and hooks
=======================

###  On this page 

1. [ Provider and typed configuration ](#content-provider-and-typed-configuration)
2. [ Custom policies and representation hooks ](#content-custom-policies-and-representation-hooks)
3. [ Events and invalidation commands ](#content-events-and-invalidation-commands)

Provider and typed configuration
--------------------------------------------------------------------------------------------------------------------------------------------------------

The provider registers defaults and a lazy service, not global middleware. Application config and container bindings override package defaults through the normal framework lifecycle.

```
use laravel::{Application, http::Response};
use spatie_responsecache::{CacheResponse, Config, service_provider};

let app = Application::configure()
    .with_providers(|providers| {
        providers.add(service_provider());
    })
    .with_config(|config, _| {
        config.set(Config {
            store: "memory".into(),
            namespace: "public-pages".into(),
            ..Config::default()
        });
    })
    .with_routing(|routing, _| {
        routing.routes(|route| {
            route.get("/", || async {
                Response::new("<h1>Blog</h1>").with_header("content-type", "text/html")
            }).middleware(CacheResponse::new());
        });
    })
    .create();
```

`Config` includes:

- `enabled`, `store`, `namespace`, and `lifetime`.
- `grace` for optional flexible caching and `max_body_bytes` for bounded collection.
- `excluded_paths`, `excluded_query_parameters`, and `excluded_request_headers`.
- `bypass` for an exact typed header/value pair. Its value is omitted from debug output.
- `ignored_query_parameters`, defaulting to `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `gclid` and `fbclid`. Set an empty vector to include every key.
- `tags` for global invalidation groups.
- `minimum_requests` with `count`, fixed-window `lifetime`, and optional separate `store`.
- Optional `DebugHeaders` with configurable status, age, time and key names. Keys are exposed only when the application's own debug mode is also enabled. Times are Unix seconds.

The provider reads these environment variables during configuration:

- `RESPONSE_CACHE_ENABLED`, default `true`.
- `RESPONSE_CACHE_DRIVER`, default `memory`. Select a shared store in production.
- `RESPONSE_CACHE_NAMESPACE`, default `public-pages`.
- `RESPONSE_CACHE_LIFETIME`, default 604800 seconds.
- `RESPONSE_CACHE_TAG`, optional global tag.
- `RESPONSE_CACHE_MINIMUM_REQUESTS`, default 1.
- `RESPONSE_CACHE_MINIMUM_REQUESTS_LIFETIME`, default 86400 seconds.
- `RESPONSE_CACHE_MINIMUM_REQUESTS_STORE`, optional counter store.
- `CACHE_BYPASS_HEADER_NAME` and `CACHE_BYPASS_HEADER_VALUE`, used together.
- `APP_DEBUG`, which enables default diagnostics.

The native environment validator rejects malformed typed values at startup. No package operation reads process environment variables at request time.

Custom policies and representation hooks
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Use the traits in `spatie_responsecache::extensions`:

- `CacheProfile` selects requests and responses, enablement, lifetime, and an asynchronous suffix. The default suffix resolves the native authenticated user identity, or empty for guests.
- `RequestHasher` controls request identity. `DefaultHasher` includes the supplied URL, suffix, and HTTP method, with length framing to prevent ambiguous concatenations. It ignores headers.
- `Replacer` transforms a stored `CachedResponse` copy with `prepare` and restores it on hits with `replace`. Both receive the current `Option<&laravel::session::Session>` and can modify status, headers and binary body. Replacers run in registration order. Changed bodies lose ETag and Content-Length. The initial response keeps its original body and headers.
- `replacers::CsrfTokenReplacer` is installed by default. `.replacer(...)` appends a hook; `.replacers(Vec<Arc<dyn Replacer>>)` replaces the complete chain, including that default.
- `Serializer` encodes and decodes a typed `CachedResponse` snapshot stored in the framework repository. `JsonSerializer` is binary-safe. Preserve all snapshot fields, including the representation ID and storage time.

For example, use a short-lived policy on news routes:

```
use std::time::Duration;
use laravel::http::Request;
use spatie_responsecache::{ResponseCache, extensions::CacheProfile};

#[derive(Debug)]
struct NewsProfile;

impl CacheProfile for NewsProfile {
    fn should_cache_request(&self, request: &Request) -> bool {
        spatie_responsecache::extensions::CacheAllSuccessfulGetRequests
            .should_cache_request(request) && !request.resembles("news/drafts/*")
    }

    fn should_cache_response(&self, response: &laravel::http::Response) -> bool {
        spatie_responsecache::extensions::CacheAllSuccessfulGetRequests
            .should_cache_response(response)
    }

    fn lifetime(&self, _: &Request, _: Duration) -> Duration {
        Duration::from_secs(30)
    }
}

let cache = ResponseCache::new("memory", "news").profile(NewsProfile);
```

Chain `.hasher(...)`, `.replacer(...)`, and `.serializer(...)` on the same handle. To use custom hooks with `CacheResponse` and the clear command, bind your configured handle:

```
use laravel::Application;
use spatie_responsecache::{ResponseCache, service_provider};

let cache = ResponseCache::new("memory", "news");
let app = Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_services(move |services| { services.instance(cache); })
    .create();
```

The middleware and command resolve the same overridden `ResponseCache`. Explicit per-route handles remain independent of that binding. `CacheResponse::new().lifetime(duration).tags(["news"])`adds route tags and overrides even the profile's lifetime. `.flexible(grace)` enables stale refresh.

Profiles own request/response policy; the base trait's eligibility methods accept everything. Delegate to `CacheAllSuccessfulGetRequests` when extending its GET/text/JSON policy, as above. Config exclusions still apply: Livewire and Inertia headers are excluded by default, but replaceable through `excluded_request_headers`. Zero lifetime disables caching. Bounded-body and trailer constraints remain in effect for every profile.

`DoNotCacheResponse` before the cache vetoes reads and writes. Inside the cache it vetoes storing a miss. Keep response-changing middleware inside the cache; authorization, session middleware and policies that must run on hits belong outside it.

Events and invalidation commands
--------------------------------------------------------------------------------------------------------------------------------------------------------

Register listeners with native `with_events` or the framework's listener attribute. Events are `CacheMissed`, `ResponseCacheHit`, `ClearingResponseCache`, `ClearedResponseCache`, and `ClearingResponseCacheFailed`. Hit payloads include URL, age in seconds, and route/global tags. Listener failures propagate. Use `laravel::event::fake()` in a `#[laravel::test]` application to assert dispatches without building another event bus.

With the provider installed, the native command supports:

- `responsecache:clear` to invalidate the configured namespace.
- `responsecache:clear --url /posts/42` for a URL relative to the application's configured URL.
- `responsecache:clear --url https://example.test/posts/42` for all representations of a URL.
- `responsecache:clear --tag posts --tag homepage` for any matching tags.

URL and tag options are mutually exclusive. Backend failures fail the command; it prints success only after invalidation completes. It never flushes the application's whole store.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
