Laravel 添加构造函数调用服务时出现 Livewire 错误 class

Laravel Livewire error when I add a constructor to call a service class

我有一段代码要重用。我读过这篇 Laravel cleaner code article and this other Laravel Services Pattern 文章,其中我意识到我可以通过使用服务 classes 在应用程序的多个位置重用代码。

在这种情况下,我在新文件夹 app/Services/MyService.

中创建了一个新 MyService class
namespace App\Services;

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

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

<?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'));
    }
}

显示的错误如下:

Argument 1 passed to App\Http\Livewire\LivewireTable::__construct() must be an instance of App\Services\MyService, string given

(但是,如果我使用一个特征,没有问题。但我担心我的特征会与以前的经验发生冲突)

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

已解决 就像 @IGP said, reading in the livewire docs 它说:

In Livewire components, you use mount() instead of a class constructor __construct() like you may be used to.

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

<?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'));
    }
}

.

Livewire's boot method Runs on every request, immediately after the component is instantiated, but before any other lifecycle methods are called

这是对我有用的解决方案。