Laravel 检查 livewire 组件是否存在

3

在渲染之前,我想要检查Livewire组件是否存在。
我的程序有模块,每个客户端都启用其中的一些模块。我可以使用$client->getModules()获取客户端拥有的模块列表。
每个模块都可以实现Livewire组件来增强程序的功能。如果这些组件存在于程序的正确部分,我就想要渲染它们。
例如,在用户创建视图中,我会有以下代码:

@foreach($client->getModules() as $module)
    if( component_exists( $module . '::users.create' ) )
        @livewire( $module . '::users.create' )
    endif;
@endforeach

如果模块实现了与用户创建相关的内容,它将拥有livewire组件 users.create ,但并不是所有模块都会增强用户创建。在渲染之前,我需要确认组件是否存在。我想知道是否有类似于 component_exists( Component::class ) 的东西,否则,我希望看到有人能够给我一些关于如何创建它作为帮助函数的提示。
1个回答

5
你可以利用 LivewireComponentsFinder 类来检查组件是否在清单中:
app(LivewireComponentsFinder::class)->getManifest();

如果您想创建一个帮助类,我已经创建了laravel-helpers。因此,您可以像这样创建一个帮助类:
function component_exists($class)
{
    $manifest = app(\Livewire\LivewireComponentsFinder::class)->getManifest();

    return (bool) array_search($class, $manifest);
}

你的答案是正确的,而且它也能正常工作,但我决定使用一个简单的PHP函数来进行检查,返回class_exists($modules_path . $module . $livewire_path . $class)。 - Tales
除了 LivewireComponentsFinder 上的 getManifest 方法之外,还有一个 find($alias) 方法,它执行答案的第二部分所做的操作... 因此更简单:app(LivewireComponentsFinder::class)->find($class); - Lochinvar

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