PHP code example of dorantor / mcounter

1. Go to this page and download the library: Download dorantor/mcounter 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/ */

    

dorantor / mcounter example snippets


class MyCounter extends \Dorantor\AbstractCounter
{
    /**
     * Method for building cache key based on $item value
     *
     * @return string
     */
    protected function getKey()
    {
        return 'myCounter' . (int) $this->item->id;
    }
}

$client = new Memcached();
// .. client setup
// 
// basically, $client creation is up to you.
// Most probably you already created one earlier, so just reuse it here.
$counter = new MyCounter($user, $client);
if ($counter->value() < 100) {
    $counter->inc();
}

$counter = new MyCounter($user, $client, 3600); // hour, in this case

protected function getExpiry()
{
    return 3600; // also hour, but this way it's defined inside counter
    // or it could be some logic based on value(s) in $this->item
}

$counter->inc();
$counter->touch();
// or
$counter->incWithTouch();

// this will delete counter, so it will be recreated
$counter->delete();

// this will get data from getInitialData() method
// and put it as current counter value
$counter->reload();

$client->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_IGBINARY);
$client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);