master

laravel/framework

Last updated at: 29/12/2023 09:20

MemcachedLock.php

TLDR

This file defines the MemcachedLock class, which extends the Lock class in the Illuminate\Cache namespace. It provides methods to create, acquire, release, and force release locks using a Memcached instance.

Classes

MemcachedLock

This class extends the Lock class and provides methods to work with locks using a Memcached instance. It has the following methods:

  • __construct($memcached, $name, $seconds, $owner = null): Initializes a new lock instance. It takes a Memcached instance, a name for the lock, the lock duration in seconds, and an optional owner value.

  • acquire(): Attempts to acquire the lock. Returns a boolean value indicating whether the lock was successfully acquired.

  • release(): Releases the lock. Returns a boolean value indicating whether the lock was successfully released.

  • forceRelease(): Releases the lock irrespective of ownership.

  • getCurrentOwner(): Returns the owner value written into the driver for this lock.

<?php

namespace Illuminate\Cache;

class MemcachedLock extends Lock
{
    /**
     * The Memcached instance.
     *
     * @var \Memcached
     */
    protected $memcached;

    /**
     * Create a new lock instance.
     *
     * @param  \Memcached  $memcached
     * @param  string  $name
     * @param  int  $seconds
     * @param  string|null  $owner
     * @return void
     */
    public function __construct($memcached, $name, $seconds, $owner = null)
    {
        parent::__construct($name, $seconds, $owner);

        $this->memcached = $memcached;
    }

    /**
     * Attempt to acquire the lock.
     *
     * @return bool
     */
    public function acquire()
    {
        return $this->memcached->add(
            $this->name, $this->owner, $this->seconds
        );
    }

    /**
     * Release the lock.
     *
     * @return bool
     */
    public function release()
    {
        if ($this->isOwnedByCurrentProcess()) {
            return $this->memcached->delete($this->name);
        }

        return false;
    }

    /**
     * Releases this lock in disregard of ownership.
     *
     * @return void
     */
    public function forceRelease()
    {
        $this->memcached->delete($this->name);
    }

    /**
     * Returns the owner value written into the driver for this lock.
     *
     * @return mixed
     */
    protected function getCurrentOwner()
    {
        return $this->memcached->get($this->name);
    }
}