Advanced components - Locking Manager - Examples.php 1.46 KB
Newer Older
hansbrix's avatar
hansbrix committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
The following code snippet demonstrates the use of Doctrine's pessimistic offline locking capabilities.

At the page where the lock is requested...
<code type="php">

// Get a locking manager instance
$lockingMngr = new Doctrine_Locking_Manager_Pessimistic();

try
{
    // Ensure that old locks which timed out are released 
    // before we try to acquire our lock
    // 300 seconds = 5 minutes timeout
    $lockingMngr->releaseAgedLocks(300);

    // Try to get the lock on a record
    $gotLock = $lockingMngr->getLock(
     // The record to lock. This can be any Doctrine_Record
                        $myRecordToLock,
    // The unique identifier of the user who is trying to get the lock
                       'Bart Simpson'
               );

    if($gotLock)
    {
        echo "Got lock!";
        // ... proceed
    }
    else
    {
        echo "Sorry, someone else is currently working on this record";
    }
}
catch(Doctrine_Locking_Exception $dle)
{
    echo $dle->getMessage();
    // handle the error
}

</code>

At the page where the transaction finishes...
<code type="php">
// Get a locking manager instance
$lockingMngr = new Doctrine_Locking_Manager_Pessimistic();

try
{
    if($lockingMngr->releaseLock($myRecordToUnlock, 'Bart Simpson'))
    {
        echo "Lock released";
    }
    else
    {
        echo "Record was not locked. No locks released.";
    }
}
catch(Doctrine_Locking_Exception $dle)
{
    echo $dle->getMessage();
    // handle the error
}
</code>