简体   繁体   中英

How to make a Controller Singleton in Laravel?

I'm making an airlines web app. Right now I'm coding de process of reserving a flight, for that purpose I have multiple views such as reserve.blade.php , chooseFlights.blade.php , passengersInfo.blade.php , etc. All those views use the same ReserveController class. The routes are specified in the web.php file like so:

Route::get('/reserve', 'ReserveController@searchFlights');
Route::get('/reserve/choose_flights', 'ReserveController@chooseFlights');
Route::post('/reserve/storeFlightsIds', 'ReserveController@storeFlightsIds');
Route::get('/reserve/passengers_info', 'ReserveController@retrievePassengersInfo');

Where those methods return the respective views with the needed data to be displayed.

The workflow of reserving is /reserve (returns the view reserve.blade.php ) that view makes a get request to -> /reserve/choose_flights (returns the view chooseFlights.blade.php ) that view makes a post request to -> /reserve/storeFlightsIds (returns the view passengersInfo.blade.php ).

In reserve.blade.php info like the origin and destiny of the desired flight, the dates and number of passengers is sent to the controller. The problem is the number of passengers is required steps further in the passengersInfo.blade.php for the view to know how many forms has to display to retrieve the info of all the passengers.

I would like to use the same instance of the ReserveController whenever a request involving it is accessed so that way I can store the needed data in properties and share the same data corresponding to the current reserve process across all those views.

Is it possible?

I would like to use the same instance of the ReserveController whenever a request involving it is accessed so that way I can store the needed data in properties and share the same data corresponding to the current reserve process across all those views.

Is it possible?

Yes its possible, you register a singleton instance in your app's service container

$this->app->singleton('MySingleton', function ($app) {
     return new SomeSharedClass(...);
});

and then you store the shared state inside that class. And inject it in your controller.

class ReserveController extends Controller 
{
     private $singleton;

     function __construct(MySingleton $singleton) {
         $this->singleton = $singleton;
     }

     ...
}

Warning!! This is not recommended. Remember if 2 different users will call the same controller method, they will also share the singleton instances. shared state is evil!

Read more about shared states here. http://henrikeichenhardt.blogspot.com/2013/06/why-shared-mutable-state-is-root-of-all.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM