【问题标题】:Constructor on Injected class not getting called Laravel IOC注入类的构造函数没有被称为 Laravel IOC
【发布时间】:2020-05-30 00:51:12
【问题描述】:

我在测试类中注入 InvoiceService。调用发票服务的create方法的测试类.. 由于这个 $repo is null 创建失败,注入类的构造函数没有被调用。 任何帮助表示赞赏。

$this->app->singleton(
    'App\Models\Subscription\Interfaces\IInvoiceService',
    'App\Models\Subscription\Impl\InvoiceService'
);



class InvoiceService implements  IInvoiceService
{

    protected $repo;


    public function _construct(){

        $this->app = App::getFacadeRoot();

        $this->repo = $this->app['repo'];


    }
    public function Create($array)
    {
    $this->repo->insert($array); // //$this->repo is null as Constructor not getting called
    }
 }


 class TestClass 

 {
    protected $InvoiceService;
    public function _construct(IInvoiceService $InvoiceService){

            $this->InvoiceService =$InvoiceService

    }

    public create($input) {

        this->InvoiceService->create($input);  // This is failing
    }
 }

【问题讨论】:

  • 什么应该回购蜜蜂?哪个班
  • $app->singleton('repo', function($app) { return new RepoManager($app); });
  • 您用于解析 repo 的语法,我没有看到(你可能是正确的)。如果你交换线路会发生什么。 $this->repo = resolve('repo');那么您也可以避免保存应用程序属性:)
  • 问题是构造函数被调用。即使我用 resolve 替换它也无济于事,因为构造函数没有被调用。
  • 你甚至没有使用构造函数

标签: laravel laravel-5 eloquent inversion-of-control


【解决方案1】:

要覆盖默认功能,您使用 __“两个下划线”,在您的示例中,您只使用一个。

_construct()

应该是。

__construct()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多