我正在使用laravel的Cache门面来建立预订数据,然后再将预订存储在数据库中。
我使用以下函数在缓存中生成预订,该函数创建一个UUID,然后将其作为预订参考。
一旦生成参考,我就将预订邮政编码设置如下
几乎所有其他预订都有冲突的邮政编码,这是缓存中另一个预订的邮政编码。
例如,当第一个客户出现时,他们的邮政编码是正确设置的。第二个客户将设置他们的邮政编码,即使我使用唯一的预订参考,这也会覆盖第一个客户的邮政编码。
缓存存储在数据库中
CACHE_DRIVER=database
BookingController.php
public function generateBooking() : JsonResponse
{
return $this->respondSuccess([
"booking_reference" => $this->booking->generate()
]);
}
public function setPostcode(string $bookingReference) : JsonResponse
{
$booking = $this->booking->setReference($bookingReference)->get();
$booking->setPostcode($this->request->postcode);
}
Booking.php
public function generate() : string
{
$this->setReference(Uuid::generate(1));
$this->store();
return $this->reference();
}
public function setReference(string $reference)
{
$this->reference = $reference;
return $this;
}
public function reference() : string
{
return $this->reference;
}
public function store($lastUpdated = true)
{
if ($lastUpdated) {
$this->lastUpdated = Carbon::now();
}
$expiresAt = now()->addMinutes(240);
$bookingAsArray = $this->parser->toArray($this);
Cache::put("bookings:".$this->reference(), $bookingAsArray, $expiresAt);
}
public function get() : Booking
{
$booking = Cache::get("bookings:".$this->reference());
return $this->parser->fromArray($this, $booking);
}
public function setPostcode($postcode, $shouldStore = true)
{
$address = Address::make([
"postcode" => $postcode
]);
if ($this->address) {
$address = $this->address;
$address->postcode = $postcode;
}
$this->address = $address;
if ($shouldStore) {
$this->store();
}
}
BookingParser.php
public function toArray(Booking $booking) : array
{
$parsedBooking = [
"reference" => $booking->reference()
];
if ($booking->address()) {
$parsedBooking["address"] = $booking->address()->toArray();
}
return $parsedBooking;
}
public function fromArray(Booking $booking, array $bookingArray) : Booking
{
$booking->setReference($bookingArray["reference"], false);
if (array_key_exists("address", $bookingArray)) {
if (array_key_exists("postcode", $bookingArray["address"])) {
$booking->setPostcode($bookingArray["address"]["postcode"], false);
}
$booking->setAddress($bookingArray["address"], false);
}
return $booking;
}