You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中PresupuestoRepository无法自动注入PacienteRepository问题

解决Laravel中PresupuestoRepository注入PacienteRepository的问题

我一眼就揪出问题根源了——你写错了PHP构造函数的方法名!PHP的构造函数是__construct(),但你在两个仓储类里都写成了__constructor()(多了一个字母r),这直接导致Laravel的服务容器识别不到这个构造函数,自然不会帮你自动注入依赖,所以$pacienteRepo才会一直是null。

下面给你一步步的修复方案:

1. 修正构造函数的方法名

把PresupuestoRepository和PacienteRepository里的__constructor()全部改成标准的__construct()。

修正后的PresupuestoRepository

<?php
namespace App\Repositories;
use Carbon\Carbon;
use App\Models\Presupuesto;
use App\Repositories\PacienteRepository;

class PresupuestoRepository extends BaseRepository {
    protected $pacienteRepo;

    // 这里改成正确的__construct()
    public function __construct(PacienteRepository $pacienteRepo) {
        // 重点:如果你的BaseRepository有自己的构造函数,必须调用父类构造
        parent::__construct();
        
        $this->pacienteRepo = $pacienteRepo;
        // 现在再测试,$pacienteRepo就不会是null了
        // dd($pacienteRepo);
    }

    public function getRepo() {
        // 这里你原来写的是$this->presupuestoRepo,应该是笔误,改成$this->pacienteRepo
        return $this->pacienteRepo;
    }
}

修正后的PacienteRepository

<?php
namespace App\Repositories;
use App\Models\Paciente;
use App\Models\Odontograma;

class PacienteRepository extends BaseRepository {
    // 同样改成正确的__construct()
    public function __construct(){}

    /**
     * @return string
     */
    public function getClassName() {
        return 'App\Models\Paciente';
    }
}

2. 别忘调用父类构造函数

如果你的BaseRepository定义了自己的构造函数(比如用来初始化模型实例),那在子类的构造函数里必须先调用parent::__construct(),否则子类的构造函数会覆盖父类的逻辑,导致父类的初始化操作无法执行,可能引发其他问题。

举个例子,如果BaseRepository是这样的:

class BaseRepository {
    protected $model;

    public function __construct() {
        $this->model = app($this->getClassName());
    }
}

那你在PresupuestoRepository的构造函数里就必须先执行parent::__construct(),再处理自己的依赖注入。

3. 验证修复效果

修改完成后,建议重启Laravel服务,如果之前用了配置或容器缓存,记得执行以下命令清除缓存:

php artisan cache:clear
php artisan config:clear

之后再访问之前的create方法,就能看到$pacienteRepo已经被正常注入了。

内容的提问来源于stack exchange,提问作者Carlos Mora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:32:31