【问题标题】:Laravel object persistence between pages页面之间的 Laravel 对象持久化
【发布时间】:2014-09-27 15:18:43
【问题描述】:

这是我的示例代码。

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
  }
}

我的路线

Route::get("/one", B@here);
Route::get("/two", B@there);

请这些只是显示一个示例。它不是正确的代码。

当第一个Route被调用的时候就ok了,相应的页面就加载好了。现在单击一个按钮,该按钮现在请求引发错误的第二页...

//在非对象上调用成员函数bar()

原因很明显,我一直在尝试查看 Laravel 是否提供了一种在页面调用之间持久化对象的方法,以及是否有人可以提供帮助。

谢谢

【问题讨论】:

    标签: php object laravel controller persistence


    【解决方案1】:

    没有很好的方法来在页面加载之间存储对象,而且实际上您永远也不想这样做。一个可能的解决方案是在类构造函数中添加您的依赖项,以便它在您的整个类中可用,如下所示:

    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
        }
    }
    

    【讨论】:

    • 是的,这发生在我身上,但遗憾的是我不太确定 Laravel 将在哪里或如何进行对象实例化,因为所有调用都是通过路由
    • @Cozzbie Laravel IoC Container 将处理注入依赖项,您无需执行任何操作。
    【解决方案2】:

    每个请求都是在内存中运行新变量的新应用程序,因此没有持久性,如果需要,您必须创建持久性代码

    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();
        }
      }
    }
    

    【讨论】:

    • 已经尝试过通过会话进行持久化,但也没有用。它不断抛出我显示的类实例错误消息。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多