LazyTrait uses trait:short
Provides a configurable "lazy" mode for classes, e.g. to provision missing resources (collections, views, tables, ...) at initialization time.
The lazy flag can be resolved from three sources, in order of priority:
- The
lazyentry of the DI container, when a container is available (checked by LazyTrait::isLazy()). - The
lazykey of an initialization array passed to LazyTrait::initializeLazy(). - The
$lazyproperty default value (true).
Example usage:
class MyModel
{
use LazyTrait;
}
$model = (new MyModel())->initializeLazy([ MyModel::LAZY => false ]);
var_dump($model->isLazy()); // false
// With a DI container, the container definition takes precedence
$container = new Container();
$container->set(MyModel::LAZY, true);
$model->initializeLazy([], $container);
var_dump($model->isLazy()); // true (from the container)
Table of Contents
Constants
- LAZY : string = 'lazy'
- The 'lazy' parameter constant.
Properties
- $container : Container
- The DI container reference.
- $lazy : bool
- The default lazy mode (provision missing resources at init).
Methods
- initializeLazy() : static
- Initialize the lazy flag.
- isLazy() : bool
- Check if lazy mode is active.
Constants
LAZY
The 'lazy' parameter constant.
public
string
LAZY
= 'lazy'
Properties
$container
The DI container reference.
public
Container
$container
$lazy
The default lazy mode (provision missing resources at init).
public
bool
$lazy
= true
Methods
initializeLazy()
Initialize the lazy flag.
public
initializeLazy([array<string|int, mixed> $init = [] ][, Container|null $container = null ]) : static
This method sets the $lazy property using the value provided in the $init array,
or falls back to the current $lazy value. Non-boolean init values are cast to boolean.
The optional $container reference is assigned to the $container property and
used later by LazyTrait::isLazy() to resolve the flag dynamically.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array, may contain a LazyTrait::LAZY key.
- $container : Container|null = null
-
Optional DI container reference.
Return values
static —Returns the current instance for chaining.
isLazy()
Check if lazy mode is active.
public
isLazy() : bool
If a DI container is assigned and defines a LazyTrait::LAZY entry,
that entry takes precedence; otherwise the $lazy property is returned.
The container value is cast to boolean.
Tags
Return values
bool —True if lazy mode is active, false otherwise.