class Context

This class is an implementation of a generic context.

Example:

// Create and set a new context, which inherits values from the current
// context and adds a new key/value pair of 'foo'/'bar'.
$prev = Context::current()->withValue('foo', 'bar')->attach();
try {
  // Do something within the context
} finally {
  // This makes sure that $prev will be current after this execution
  Context::current()->detach($prev);
}
// Here, we are 100% sure $prev is the current context.

Methods

__construct(array $initialValues = [])

Creates a new Context.

withValue(string $key, mixed $value)

Creates a new context with the given key/value set.

withValues(array $data)

Creates a new context with the given key/values.

mixed
value(string $key, mixed $default = null)

Fetches the value for a given key in this context. Returns the provided default if not set.

array
values()

Returns all the contained data.

attach()

Attaches this context, thus entering a new scope within which this context is current(). The previously current context is returned.

detach(Context $toAttach)

Reverses an attach(), restoring the previous context and exiting the current scope.

static Context
current()

Returns the context associated with the current scope, will never return null.

static Context
background()

Returns an empty context.

Details

at line 54
__construct(array $initialValues = [])

Creates a new Context.

Parameters

array $initialValues

at line 66
Context withValue(string $key, mixed $value)

Creates a new context with the given key/value set.

Parameters

string $key
mixed $value

Return Value

Context

at line 79
Context withValues(array $data)

Creates a new context with the given key/values.

Parameters

array $data

Return Value

Context

at line 96
mixed value(string $key, mixed $default = null)

Fetches the value for a given key in this context. Returns the provided default if not set.

Parameters

string $key
mixed $default [optional]

Return Value

mixed

at line 108
array values()

Returns all the contained data.

Return Value

array

at line 119
Context attach()

Attaches this context, thus entering a new scope within which this context is current(). The previously current context is returned.

Return Value

Context

at line 132
detach(Context $toAttach)

Reverses an attach(), restoring the previous context and exiting the current scope.

Parameters

Context $toAttach

at line 147
static Context current()

Returns the context associated with the current scope, will never return null.

Return Value

Context

at line 161
static Context background()

Returns an empty context.

Return Value

Context