我有一段想要重用的代码。我读了这篇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'));
}
}
显示的错误如下所示:
(然而,如果我使用trait,则没有问题。但我担心我的traits会与以前的经验冲突)传递给App\Http\Livewire\LivewireTable::__construct()的第一个参数必须是App\Services\MyService的实例,但提供了字符串
我该如何修复它? 我错过了什么?
mount()
而不是__construct()
? - IGP