当我添加一个构造函数来调用服务类时,Laravel Livewire出现错误。

9

我有一段想要重用的代码。我读了这篇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()的第一个参数必须是App\Services\MyService的实例,但提供了字符串

(然而,如果我使用trait,则没有问题。但我担心我的traits会与以前的经验冲突)
我该如何修复它? 我错过了什么?

5
你是如何调用Livewire类的?你是否尝试使用mount()而不是__construct() - IGP
确实,在文档中(https://laravel-livewire.com/docs/2.x/rendering-components#parameters)确实如此!这就是诀窍。非常感谢! - Pathros
2个回答

9
Livewire 的 boot 方法会在每个请求时运行,组件实例化后立即运行,但在调用任何其他生命周期方法之前。

以下是对我有效的解决方案。

public bool $checkAllRecords = false;

public array $checkedRecords = [];

private MailService $service;

public function boot(MailInterface $service)
{
    $this->service = $service;
}

public function updatingCheckAllRecords($value)
{
    $this->checkRecords = $value ? (array) $this->service->getListData($this->perPage, $this->search)->pluck('id') : []
}

9

已解决 就像@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'));
        }
    }

当您在Livewire组件内部时,可以使用mount()方法注入服务类。 - Theodory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接