提问人:MrCujo 提问时间:8/31/2022 更新时间:8/31/2022 访问量:35
Laravel:php match似乎不起作用
Laravel: php match does not seem to be working
问:
我正在开发一个 Laravel 应用程序。我创建了一个这样的枚举:
<?php
namespace Domain\Order\Enums;
use Domain\Order\Models\Order;
enum OrderStatuses : string
{
case New = 'new';
case Pending = 'pending';
case Canceled = 'canceled';
case Paid = 'paid';
case PaymentFailed = 'payment-failed';
public function createOrderStatus(Order $order) : OrderStatus
{
return match($this) {
OrderStatuses::Pending => new PendingOrderStatus($order),
OrderStatuses::Canceled => new CanceledOrderStatus($order),
OrderStatuses::Paid => new PaidOrderStatus($order),
OrderStatuses::PaymentFailed => new PaymentFailedOrderStatus($order),
default => new NewOrderStatus($order)
};
}
}
在我的订单模型中,我有以下属性:
protected function status(): Attribute
{
return new Attribute(
get: fn(string $value) =>
OrderStatuses::from($value)->createOrderStatus($this),
);
}
如您所见,它接收一些数据并返回订单状态。
现在,我有了以下一段代码:
$order = Order::find($orderID);
$newOrder = match ($order->status) {
OrderStatuses::New => (new NewToPaidTransition)->execute($order),
NewOrderStatus::class => (new NewToPaidTransition)->execute($order),
'new' => (new NewToPaidTransition)->execute($order),
default => null,
};
但 的值始终是 ,这意味着状态没有与任何元素匹配。那里应该有一个元素:,我只是出于调试目的添加了其他元素。$newOrder
null
NewOrderStatus::class
如果我在运行调试器时检查值,我会得到它的类型,那么为什么它不匹配呢?$order->status
Domain\Order\Enums\NewOrderStatus
谢谢
答:
0赞
levi
8/31/2022
#1
看起来您正在测试类的实例和类名的字符串之间的相等性。
尝试
$newOrder = match (get_class($order->status)) {
OrderStatuses::New => (new NewToPaidTransition)->execute($order),
NewOrderStatus::class => (new NewToPaidTransition)->execute($order),
'new' => (new NewToPaidTransition)->execute($order),
default => null,
};
评论
0赞
MrCujo
8/31/2022
这奏效了,谢谢。我添加到我的模型中,认为它可能在不使用的情况下工作,但事实并非如此protected $casts = [ 'status' => OrderStatuses::class, ];
get_class
下一个:显示不同表中的名称而不是 ID
评论