在 laravel/livewire 站点上,我尝试使用依赖注入来定义服务类 用于键/值写入读取。
我定义了2个类,app/Library/Services/Interfaces/KeyDataInterface.php :
<?php
namespace App\Library\Services\Interfaces;
use App\Models\KeyData;
/**
* Write/read key value into/from storage
*/
interface KeyDataInterface
{
/**
* Write key/value into storage
*
* @param string $key
* @param string $value
* @param int $durationInSeconds
*
* @return KeyData - created model
*/
public static function write( string $key, string $value, int $durationInSeconds = 60 ): KeyData;
}
并在 app/Library/Services/KeyDataInDbService.php 中实现:
<?php
namespace App\Library\Services;
use App\Library\Services\Interfaces\KeyDataInterface;
use App\Models\KeyData;
use Carbon\Carbon;
/**
* Write/read key value into/from db
*
*/
readonly class KeyDataInDbService implements KeyDataInterface
{
/**
* Write key/value into db
*
* @param string $key
* @param string $value
* @param int $durationInSeconds
*
* @return KeyData - created model
*/
public static function write( string $key, string $value, int $durationInSeconds = 60 ): KeyData {
$keyData = KeyData::getByKey($key)->getByValue($value)->first();
// scopeGetByValue
if(!empty($keyData)) {
$keyData->expired_at = Carbon::now('UTC')
->addSeconds($durationInSeconds);
return $keyData;
}
return KeyData::create([
'key' => $key,
'value' => $value,
'expired_at' => Carbon::now('UTC')->addSeconds($durationInSeconds)
]);
}
}
我将它们绑定在 app/Providers/AppServiceProvider.php 中:
public function register(): void
{
$this->app->bind(
'App\Library\Services\Interfaces\KeyDataInterface',
'App\Library\Services\KeyDataInDbService'
);
}
但是当我尝试在 livewire 组件中使用 is 时:
class TheTaskIsViewed extends Component
{
...
public KeyDataInterface $keyDataService;
public function boot(KeyDataInterface $keyDataService)
{
$this->keyDataService = $keyDataService;
}
public function mount(int $taskId)
{
我遇到错误:
Property type not supported in Livewire for property: [{}]
在浏览器中,我看到指向一个只有 8 行的文件的第 12 行:
组件 TheTaskIsViewed 在 resources/views/livewire/test.blade.php 上使用为:
<div class="admin_page_container" id="app_image_admin_page_container pt-64" x-cloak>
<fieldset class="p-1 m-1 mb-6 bordered">
<legend class="bordered">
the-task-is-viewed
</legend>
<livewire:admin.the-task-is-viewed taskId="5"/>
</fieldset>
</div>
为什么我收到此错误以及如何修复它?
"laravel/framework": "^10.48.4",
"livewire/livewire": "^3.4.9",
提前致谢!
在Livewire的public属性中,仅支持某些类型。 https://livewire.laravel.com/docs/properties#supported-property-types
如果您不在视图中使用
$keyDataService
,请将其设为私有或受保护。
protected KeyDataInterface $keyDataService;
如果您想在视图中使用
$keyDataService
,请创建自定义类型。