首页 > 解决方案 > 当我添加构造函数来调用服务类时,Laravel Livewire 错误

问题描述

我有一段要重用的代码。我已经阅读了Laravel 清洁代码文章和其他Laravel 服务模式文章,在那里我意识到我可以通过使用服务类在应用程序的多个位置重用代码。

在这种情况下,我在MyService新文件夹中创建了一个新类app/Services/MyService

namespace App\Services;

class MyService
{
    public function reuse_code($param){
       return void;
    }
}

当我想通过 Livewire 类组件内部的构造函数调用该类时,问题就来了,如下所示:

<?php

namespace App\Http\Livewire;

use App\Services\MyService;
use Livewire\Component;
use Livewire\WithPagination;

class LivewireTable extends Component
{
    use WithPagination;

    private $myClassService;

    public function __construct(MyService $myService)
    {
        $this->myClassService = $myService;
    }

    public function render()
    {
       $foo = $this->myClassService->reuse_code($param);
       return view('my.view',compact('foo'));
    }
}

显示的错误如下:

传递给 App\Http\Livewire\LivewireTable::__construct() 的参数 1 必须是 App\Services\MyService 的实例,给定字符串

(但是,如果我使用特质,就没有问题。但我担心我的特质会像以前的经历一样发生冲突)

我如何解决它?我错过了什么?

标签: laravellaravel-livewire

解决方案


解决了 就像@IGP说的,在livewire 文档中阅读它说:

在 Livewire 组件中,您使用 mount() 而不是类构造函数 __construct() ,就像您可能习惯的那样。

所以,我的工作代码如下:

<?php

namespace App\Http\Livewire;

use App\Services\MyService;
use Livewire\Component;
use Livewire\WithPagination;

class LivewireTable extends Component
{
    use WithPagination;

    private $myClassService;

    public function mount(MyService $myService)
    {
        $this->myClassService = $myService;
    }

    public function render()
    {
       $foo = $this->myClassService->reuse_code($param);
       return view('my.view',compact('foo'));
    }
}

.


推荐阅读