PHP code example of kaihiro / optimistic-lock

1. Go to this page and download the library: Download kaihiro/optimistic-lock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kaihiro / optimistic-lock example snippets



use OptimisticLock\Model\OptimisticLockTableTrait;
class PostsTable extends Table
{
    // Add the trait to your table
    use OptimisticLockTableTrait;

    public function initialize(array $config)
    {
        // Add the behaviour to your table
        $this->addBehavior('OptimisticLock.OptimisticLock');
	}
}


use OptimisticLock\Exception\OptimisticLockException;
class PostsController extends AppController
{
    public function edit($id = null)
    {
        $post = $this->Posts->get($id);

        if ($this->request->is(['patch', 'post', 'put'])) {
            try {
            	$post = $this->Posts->patchEntity($post, $this->request->data);
                if ($this-> Posts->save($post)) {
                    $this->Flash->success(__('The post result has been saved.'));

                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The post could not be saved. Please, try again.'));
                }

            // You can handle optimistic lock by catching OptimisticLockException.
            } catch (OptimisticLockException $e) {
                $this->Flash->error(__('optimistic lock error.'));
            }
        }
        $this->set(compact('post'));
        $this->set('_serialize', ['post']);
    }