Skip to content

FuncService Resolves Deps Early #20

@XedinUnknown

Description

@XedinUnknown

Usecase

FuncService is a convenient way to create a simple invocable service. One use-case for this is a function that retrieves some configuration at call time, which could help facilitate lazy loading. Let's say, I have a block that, when rendered on a page, must fetch some data from an API, and display it. To render, it needs some configuration that may not yet be available at application load time - because it has yet to be fetched; but it has no use for it before, and thus loading this configuration (e.g. from the API) must not happen until and unless the block renders. With the new ability to specify whole service definitions as dependencies, it could be as simple as:

[
    'my-block-service' => new Constructor(MyBlock::class, [
        new FuncService(['service-that-is-only-required-during-rendering'], fn(ServiceType $service): ServiceType => $service),
    ]),
];

class MyBlock
{
    /**
     * @param callable(): ServiceType $getServiceForRendering Retrieves the service that's necessary to render the block
     */
    public function __construct(protected callable $getServiceForRendering)
    {
        // Service is not yet loaded; only its "getter"
    }

    public function render()
    {
        $service = ($this->getServiceForRendering)();
        // Do something with the service, which is only retrieved during rendering
    }
}

The Problem

FuncService resolves dependencies when it is resolved, rather than when the callable it returns is invoked. This necessitates that service-that-is-only-required-during-rendering is available during MyBlock's initialisation, which is way before it is used, if ever.

Suggested Solution

Make FuncService resolve dependencies when invoked, rather than when it is resolved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions