Here's my sample code.
class A {
public function foo(){
}
public function bar(){
}
}
class B {
$one;
function here(){
$this->one = new A();
$this->one->foo();
return View::make("route1"); //This is ok, no problems
}
function there(){
$this->one->bar(); //ERROR: Call to a member function bar() on a non-object
}
}
My routes
Route::get("/one", B@here);
Route::get("/two", B@there);
Please these just show a sample. Its not the code proper.
When the first Route is called all is ok, and the corresponding page is loaded. Now on a button click which now requests the second page that error is thrown...
//Call to a member function bar() on a non-object
Its obvious the cause for this and I have been trying to see if Laravel offers a way to persist objects in between page calls and if someone can please help.
Thanks
There is no nice way to store objects between page loads and really you would never want to do that anyway. A possible solution would be to add your dependency in the class constructor so it available throughout your class like this:
class A {
public function foo(){}
public function bar(){}
}
class B {
protected $one;
public function __construct(A $one)
{
$this->one = $one;
}
public function here()
{
$this->one->foo(); // Available
}
public function there()
{
$this->one->bar(); // Available
}
}
Every request is a new application running with new variables in memory, so there is no persistence, you have to create your persistence code, if you need them
class B {
$one;
function here()
{
$this->one = new A();
$this->one->foo();
Session::put('one', $this->one); // persist it using Session
return View::make("route1"); //This is ok, no problems
}
function there()
{
if (Session::has('one'))
{
$one = Session::get('one'); /// get your data back from session
$one->bar();
}
}
}