Laravel5.5 构造方法中使用依赖注入得不到数据

问题:为什么在同一个控制器中构造方法中使用依赖注入就无数据呢?因为我要注入的方法有很多,所以想在构造方法中实现

情景1

namespace App\Http\Controllers\Admin;

use App\Customer;
use App\CustomerAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CustomerAddressController extends Controller\
{

    protected $customer;

    public function __construct(Customer $Customer)
    {
        $this->customer  = $Customer;
    }

    public function index()
    {
        dd($this->customer);
    }

        }

这种情况打印出来的对象没有数据。

情景2:


namespace App\Http\Controllers\Admin;

use App\Customer;
use App\CustomerAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CustomerAddressController extends Controller\
{

    protected $customer;

    public function __construct()
    {

    }

    public function index(Customer $Customer)
    {
        dd($Customer);
    }

        }

这种情况打印出来的对象有数据。

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
arunfung
最佳答案

@qIXbwU11 解释下为什么是这样的,通过对应方法的注入,laravel帮我们做了路由模型绑定,而且正好触发了隐式绑定,所以可以取得到数据,但是构造方法的注入,仅仅只是把模型注入到类中,所以是无法取得数据的。

4年前 评论
讨论数量: 7
arunfung

麻烦 Customer 类也贴一下

4年前 评论

@arunfung Customer类,是这样吗?这个类里面没相关的代码,基本上就是这样的结构了。

namespace App\Http\Controllers\Admin;

use App\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class CustomerController extends Controller
{
public function __construct()
{
xxxxxxxx;
}

}

4年前 评论
arunfung

@qIXbwU11 :joy:是你要注入的类,就是model,一般正常直接在控制器中获取数据就好,like this
model中有很多可以使用的方法,仔细去探究一下

namespace App\Http\Controllers\Admin;

use App\Customer;
use App\CustomerAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CustomerAddressController extends Controller
{

    protected $customer;

    public function __construct(Customer $Customer)
    {
        $this->customer  = $Customer;
    }

    public function index()
    {
        dd($this->customer->all());
    }

}
4年前 评论

我明白注入的是model,所以在CustomerAddressController,注入Customer的model

我来详细解释一下,我的意思是这样的:
首先路由是这样的,当访问admin/customer/1234/address的时候,久会自动注入ID=1234所对应的Customer里面的模型
Route::resource('admin/customer/{Customer}/address','Admin\CustomerAddressController');

现在的问题是,当我采用正文情景1的方法,通过构造方法自动给该控制器的所有方法注入ID=1234的Customer的模型。
结果打印出来无数据,如下图。

file

当采用正文情景2的方法,直接注入,结果却有数据,如下图

file

4年前 评论
arunfung

@qIXbwU11 解释下为什么是这样的,通过对应方法的注入,laravel帮我们做了路由模型绑定,而且正好触发了隐式绑定,所以可以取得到数据,但是构造方法的注入,仅仅只是把模型注入到类中,所以是无法取得数据的。

4年前 评论

@arunfung 大神就是大神!!! 厉害!!! 终于知道原因了,要不太难受了。看来我要分别在每个方法注入了。

4年前 评论
arunfung

@qIXbwU11 每个方法注入那就不优雅了啊,你可以稍微优雅一点

public function index($customer)
{
        $customer = $this->customer->find($customer);         //返回一个模型
        $customer = $this->customer->findOrFail($customer);      //找不到抛出异常
 }
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!