Using wallet methods throughout the program in laravel

31 Views Asked by At

I created a wallet in Laravel that I want the operations of this wallet to be stored in one place and can be used in the whole program, for example:

WalletClass::deposit(25000,auht()->id());

Which method should I use? Is it better to write a service provider or fecads and... or do we have a better method? thanks

1

There are 1 best solutions below

3
Tony On

If you only need one instance of the Wallet shared across the entire application you can register a singleton.

This allows you to use App::make(WalletClass) anywhere and get the same instance.

The singleton method binds a class or interface into the container that should only be resolved one time.

Be careful though, do you really want every request sharing the same object? For something like a wallet it would like you would need an instance per connection. If that's the case you can use a scoped singleton.

The scoped method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle

Regarding the naming of your class, it's generally not a good idea to suffix everything with what it is, such as WalletClass or WalletInterface. What's wrong with just calling it a Wallet?