Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] ShouldBeSingleton interface as an alternative syntax to registering singletons #52334

Closed
wants to merge 1 commit into from

Conversation

cosmastech
Copy link
Contributor

@cosmastech cosmastech commented Jul 31, 2024

Working on an enterprise-level application, the AppServiceProvider gets pretty large. Almost every service we have created really should be bound as a singleton, but sometimes we either don't want to pollute the AppServiceProvider, or we simply forget.

This is a slightly cleaner syntax. We simply add implements ShouldBeSingleton to the classes.

class CreatePodcastAction implements ShouldBeSingleton
{
    public function __construct(
        private readonly AwsService $awsService,
        private readonly SomeOtherService $anotherService,
        // ... more complex objects to resolve
    ) {
    }
}

As an alternative to adding:

// AppServiceProvider
// ... all of the other singletons we have bound
$this->app->singleton(CreatePodcastAction::class);

Followup

Add a ShouldBeScopedSingleton interface so we can leverage this and place nice with Laravel Octane.

Copy link

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@cosmastech cosmastech force-pushed the should-be-singleton branch from 9a39ca2 to 768db7d Compare July 31, 2024 00:09
@cosmastech cosmastech marked this pull request as ready for review July 31, 2024 00:13
@yoeriboven
Copy link
Contributor

You could also just create a new service provider in which you register all singletons.

@cosmastech
Copy link
Contributor Author

You could also just create a new service provider in which you register all singletons.

Very true. This is just a suggestion for a little quality of life improvement.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants