> For the complete documentation index, see [llms.txt](https://core-foundation-doc.rupeshstha.com.np/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://core-foundation-doc.rupeshstha.com.np/architecture-and-concepts/application-context.md).

# Application Context

`ApplicationContext` is a collision-safe, typed wrapper around Laravel's `Context` facade. It ensures that different domains in a modular monolith can store state without accidentally overwriting each other's keys.

## Why Use ApplicationContext?

Laravel's `Context` is a flat global key-value store. `ApplicationContext` adds discipline by:

* Enforcing a **mandatory namespace prefix** per domain.
* Separating **public context** (logged automatically) from **hidden context** (sensitive data).
* Providing a **typed API** instead of raw string keys.

## Creating a Context Class

Each domain should create its own subclass of `ApplicationContext`.

```php
namespace App\Modules\Orders;

use CoreFoundation\Services\ApplicationContext;

class OrderContext extends ApplicationContext
{
    // Mandatory unique prefix for this domain
    protected function prefix(): string
    {
        return 'order';
    }

    // Public context (appears in logs)
    public function setOrderId(int $id): static
    {
        return $this->set('order_id', $id);
    }

    public function getOrderId(): ?int
    {
        return $this->get('order_id');
    }

    // Hidden context (never written to logs)
    public function setPaymentToken(string $token): static
    {
        return $this->setHidden('payment_token', $token);
    }
}
```

## Usage

You can use the static `make()` factory for fluent chaining:

```php
OrderContext::make()
    ->setOrderId(123)
    ->setPaymentToken('tok_secret_123');
```

In your logs, public context keys will be stored as `{prefix}.{key}`:

* `order.order_id: 123`

## Public vs Hidden Context

| Context Type | Method                       | behavior                                                   |
| ------------ | ---------------------------- | ---------------------------------------------------------- |
| **Public**   | `set()`, `get()`             | Appended to all log entries automatically.                 |
| **Hidden**   | `setHidden()`, `getHidden()` | Never written to logs. Survives request-to-queue boundary. |

## Advanced Features

### Counters

Increment or decrement values in public context:

```php
$context->increment('attempt_count');
```

### Stacks

Maintain ordered lists (useful for breadcrumbs or audit trails):

```php
$context->push('steps', 'validation_passed', 'payment_initiated');
```

### Snapshots

Retrieve all state belonging to this domain:

```php
$data = $context->snapshot(); // Returns ['order_id' => 123, ...]
```
