Skip to content

Latest commit

 

History

History
82 lines (59 loc) · 2.23 KB

object.md

File metadata and controls

82 lines (59 loc) · 2.23 KB

Objects

object() declares a class as a service and returns its Ref<T>. Constructor parameters are autowired, so the common case is a single call:

$mailer = $dic->object(Mailer::class); // Ref<Mailer>

See:

Custom factory

Pass a factory as the second argument to build the instance yourself instead of calling the constructor. The factory's own parameters are autowired, exactly like constructor arguments.

It can be any of:

  • a plain callable — a closure, a static factory method, an invokable;
  • a [Ref<object>, 'method'] pair, to build the instance with a method of another service;
  • a Ref<callable> — another callable service.
$dic->object(Mailer::class, Mailer::fromConfig(...));

$factory = $dic->object(MailerFactory::class);
$dic->object(Mailer::class, [$factory, 'create']);

A method can also be wired the other way around, from the factory object's own config, with method():

$dic->object(
    class: Mailer::class,
    factory: $dic->object(MailerFactory::class)->method('create'),
);

Post-construction calls

Use call() for a setter or any side-effecting method invoked after construction:

$dic
    ->object(Mailer::class)
    ->call('setLogger', args: [$logger]);

Use chain() when the method returns the value to keep, as with immutable (wither-style) objects:

$dic
    ->object(Mailer::class)
    ->chain('withRetries', args: [5]);

Both accept the method's args and a variadic, just like declaring a service — see Arguments:

$dic
    ->object(Logger::class)
    ->call('pushHandlers', variadic: [$stderrHandler, $fileHandler]);

Lazy instantiation

lazy() defers construction until the service is first used, returning a lazy proxy in the meantime; eager() undoes it:

$dic
    ->object(Mailer::class)
    ->lazy();

This relies on PHP 8.4 lazy objects, so the class passed to object() must be instantiable and support them.