If I have initialized an object, somewhere, Idk how to do this, so, somewhere
$sharedObject = new sharedClass();
Supposing I have two routes in web.php:
Route::get('/page1', function(){
$sharedObject->setFoo('newVal');
return $sharedObject->getFoo();
});
Route::get('/page2', function(){
return $sharedObject->getFoo();
});
So, is there a way to achieve this functionality, I just want to access the properties I had set in the original instantiation of an object, through another route?
If I have initialized an object, somewhere, Idk how to do this, so, somewhere
$sharedObject = new sharedClass();
Supposing I have two routes in web.php:
Route::get('/page1', function(){
$sharedObject->setFoo('newVal');
return $sharedObject->getFoo();
});
Route::get('/page2', function(){
return $sharedObject->getFoo();
});
So, is there a way to achieve this functionality, I just want to access the properties I had set in the original instantiation of an object, through another route?
Share Improve this question asked Mar 25 at 14:28 GursimranjitGursimranjit 411 silver badge6 bronze badges 4 |1 Answer
Reset to default 3I'm not sure if it will meet your requirements, but there are 2 ways to share the same object.
- Sessions
- Cache
Sessions are mostly used for saving logged in user's information for a short time (depends on the session lifetime setting).
Cache is used to store heavy computational data temporarily and can be immediately retrieved.
You can implement through the following:
use Illuminate\Http\Request;
// Session
Route::get('/page1', function(Request $request){
$sharedObject = new SharedObject();
$sharedObject->setFoo('newVal');
$request->session()->put('sharedObject', $sharedObject);
return $sharedObject->getFoo();
});
Route::get('/page2', function(Request $request){
$sharedObject = $request->session()->get('sharedObject');
return $sharedObject->getFoo();
});
// Cache
Route::get('/page1', function(Request $request){
$sharedObject = cache('sharedObject');
if (is_null($sharedObject)) {
$sharedObject = new SharedObject();
$sharedObject->setFoo('newVal');
cache(['sharedObject' => $sharedObject], now()->addHour()); // store for an hour.
}
return $sharedObject->getFoo();
});
Route::get('/page2', function(Request $request){
$sharedObject = cache('sharedObject');
return $sharedObject->getFoo();
});
Just make sure that your $sharedObject
can be serializable. I believe laravel will store the data as a serialized string.
$sharedObject
withuse
for your functions, although I don't know (one way or another) if that's the recommended pattern for Laravel. Second, you understand that thesetFoo()
in the first route won't have any effect on thegetFoo()
in the second route, right? – Chris Haas Commented Mar 25 at 14:43