ServerSideScripting.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. require 'SharedConfigurations.php';
  11. // This example will not work with versions of Redis < 2.6.
  12. //
  13. // Additionally to the EVAL command defined in the current development profile,
  14. // the Predis\Command\ScriptCommand class can be used to build an higher level
  15. // abstraction for "scriptable" commands so that they will appear just like any
  16. // other command on the client-side. This is a quick example used to implement
  17. // INCREX.
  18. use Predis\Command\ScriptCommand;
  19. class IncrementExistingKeysBy extends ScriptCommand
  20. {
  21. public function getKeysCount()
  22. {
  23. // Tell Predis to use all the arguments but the last one as arguments
  24. // for KEYS. The last one will be used to populate ARGV.
  25. return -1;
  26. }
  27. public function getScript()
  28. {
  29. return
  30. <<<LUA
  31. local cmd, insert = redis.call, table.insert
  32. local increment, results = ARGV[1], { }
  33. for idx, key in ipairs(KEYS) do
  34. if cmd('exists', key) == 1 then
  35. insert(results, idx, cmd('incrby', key, increment))
  36. else
  37. insert(results, idx, false)
  38. end
  39. end
  40. return results
  41. LUA;
  42. }
  43. }
  44. $client = new Predis\Client($single_server);
  45. $client->getProfile()->defineCommand('increxby', 'IncrementExistingKeysBy');
  46. $client->mset('foo', 10, 'foobar', 100);
  47. var_export($client->increxby('foo', 'foofoo', 'foobar', 50));
  48. /*
  49. array (
  50. 0 => 60,
  51. 1 => NULL,
  52. 2 => 150,
  53. )
  54. */