Tutorial - counters

Counters are shared integer counters for all connected clients, mainly to be used for interclient communication. You can add, substract, set and unset values. As like all other scached's data values, counters are destroyed on scached's crash or restart so counters are not right tool for unique numbering of something. Instead counters can be tool for inter-session synchronization especially when used with scache_iov

Counters support setting values with scache_vset, incrementing values with scache_vadd, decrementing values with scache_vsub, unsetting values with scache_vunset and querying values with scache_vget. There is no "exists" -function. Actually all unexisting values are interpreted and returned as integer "0".

Incrementing and decrementing return value resulted after completion, setting and unsetting return counters previous value. As like other functions, counters support paths which must be taken into account if creating subvalues for previously existing counter. Counters' keyspace is separate for all other, so paths used doesn't collide with others.

$conn = scache_reset('Example');

scache_vset($conn, 'path/to/value', 1); // returns 0

scache_vget($conn, 'path/to/value');    // returns 1
scache_vadd($conn, 'path/to/value', 4); // returns 5
scache_vsub($conn, 'path/to/value', 2); // returns 3
scache_vunset($conn, 'path/to/value');  // returns 3

scache_vadd($conn, 'path/to/unexistent', 4); // returns 4
scache_vget($conn, 'path/to/unexistent');    // returns 4

/* note that get doesn't replace values, but set does */
scache_vset($conn, 'path/to', 5);       // returns 0
scache_vget($conn, 'path/to/value');    // returns 0 
scache_vget($conn, 'path/to');          // returns 5 (get didn't replace)
scache_vset($conn, 'path/to/value', 2); // returns 0
scache_vget($conn, 'path/to');          // returns 0 (set replaced parent)

Misc notes

Counters are always 64-bit wide on scached backend regardless of scached being run on 32bit or 64bit platform. Values are instead truncated to php's native interger limits in querying client's php extension. Careless mixing of 64bit and 32bit clients using same counters might lead for example :

$conn = scache_reset('Example');

scache_vset($conn, 'counter', 2147483647); // 0x7fffffff
scache_vadd($conn, 'counter', 1);

/* counter queried on 32-bit platform */
scache_vget($conn, 'counter'); // results -2147483648 (0x80000000)

/* counter queried on 64-bit platform */
scache_vget($conn, 'counter'); // results 2147483648 (0x80000000)

Besides of using counters as content version tagging, in real life it might be hard to find more sensible uses for counters. They are added just because it was so easy to add them.