php - 类的实例化如何适用于 Laravel 中的不同路线

标签 php laravel

也许我的问题很模糊,所以让我说清楚。我创建了一个 Controller 文件,例如 SomeController.php ,在我的 LoginController 中我有:

use SomeController;

private $instance;

public function someRouteDefinedInRouteFile() {
   $this->instance = new SomeController; // now $this->instance must have SomeController instance
   return $this->instance;
}

public function someOtherRoute() {
   return $this->instance;  // it must return the instance but it's null
}

如果someRouteDefinedInRouteFile()被调用,$this->instance必须有SomeController的实例。但是调用 someAnotherRoute() 后,$this->instance 为 null

最佳答案

这是因为这些方法是在单独的请求期间执行的。如果您想使用同一个实例,请使用 IoC将类注入(inject) Controller 构造函数中。

protected $istance;
public function __construct(Instance $instance)
{
    $this->instance = $instance;
}

然后您就可以在任何 Controller 的方法中使用它。

关于php - 类的实例化如何适用于 Laravel 中的不同路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48334917/

相关文章:

Laravel JSON API : How to create custom virtual resource from database (for aggregated values)?

php - Laravel View 不适合 dompdf 生成的 pdf

php - 使用 PDO_MYSQL 与 Zend_Db::factory 连接超时

javascript - 使用 jquery 刷新 php 并重新加载图像

laravel - 将数据传递到所有路由?

php - 从 Laravel 查询构建器中获取具有 elquent 关系的数据

php - 使用 Eloquent 从 Laravel 5 中的 Blade 运行选择查询的正确方法

php - 将 json 对象传递给数组 - 自动完成

php - 如何使用 php curl 在 Mandrill 中附加 Excel 文件

php - fatal error : Call to a member function bind_param() on a non-object when updating