问题描述
在laravel-livewire /项目中,我需要使用存储库。 我发现了图书馆https://github.com/andersao/l5-repository 并查看示例如何将存储库分配给PostsController
namespace App\Http\Controllers;
use App\PostRepository;
class PostsController extends BaseController {
protected $repository;
public function __construct(PostRepository $repository){
$this->repository = $repository;
}
....
}
我尝试使component相似:
use App\Repositories\Interfaces\FacilityRepositoryInterface;
class Facilities extends Component
{
use WithPagination;
public $form= [
'name'=>'','descr'=> '','created_at'=> '','is_reopen' => false,];
public $current_facility_id;
public $filter_name= '';
public $updateMode = 'browse';
protected $FacilityRepository;
public function __construct(FacilityRepositoryInterface $FacilityRepository)
{
$this->FacilityRepository = $FacilityRepository;
}
public function render()
{
$backend_per_page = Settings::getValue('backend_per_page',CheckValueType::cvtInteger,20);
$this->emit('facility_opened',[ 'mode'=>'browse','id'=>null ] );
return view('livewire.admin.facilities.container',[
'facilityDaTarows' => $this->FacilityRepository->filterWithPagination(
[
'name'=>$this->filter_name,'per_page'=> $backend_per_page
]
),'facility_rows_count'=> $this->facility_rows_count
]);
}
其中filterWithPagination是的方法
class FacilityRepository extends BaseRepository implements FacilityRepositoryInterface
{
private $UserRepository;
...
I found deFinition of __construct in in vendor/livewire/livewire/src/Component.PHP as :
public function __construct($id)
{
$this->id = $id;
$this->ensureIdPropertyIsntOverridden();
$this->initializeTraits();
}
有一种有效的方法吗?
谢谢!
解决方法
您应该使用mount
方法进行依赖项注入
这应该可行
class Facilities extends Component {
public function mount(FacilityRepositoryInterface $FacilityRepository) {
$this->FacilityRepository = $FacilityRepository;
}
}
查看文档:{{3}}
,我也有同样的担忧。我认为livewire当前不支持依赖项注入。您现在可以做的就是将您的存储库注入mount方法。
public function mount(FacilityRepositoryInterface $FacilityRepository)
{
$this->FacilityRepository = $FacilityRepository;
}
,
如果你的 action 需要任何应该通过 Laravel 的依赖注入容器解析的服务,你可以在任何附加参数之前在 action 的签名中列出它们
public function addTodo(TodoService $todoService,$id,$name)
{
...
}