ServerSideScripting.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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, the new
  14. // Predis\Command\ScriptedCommand base class can be used to build an higher abstraction
  15. // for our "scripted" commands so that they will appear just like any other command on
  16. // the client-side. This is a quick example used to implement INCREX.
  17. use Predis\Command\ScriptedCommand;
  18. class IncrementExistingKeysBy extends ScriptedCommand
  19. {
  20. public function getKeysCount()
  21. {
  22. // Tell Predis to use all the arguments but the last one as arguments
  23. // for KEYS. The last one will be used to populate ARGV.
  24. return -1;
  25. }
  26. public function getScript()
  27. {
  28. return
  29. <<<LUA
  30. local cmd, insert = redis.call, table.insert
  31. local increment, results = ARGV[1], { }
  32. for idx, key in ipairs(KEYS) do
  33. if cmd('exists', key) == 1 then
  34. insert(results, idx, cmd('incrby', key, increment))
  35. else
  36. insert(results, idx, false)
  37. end
  38. end
  39. return results
  40. LUA;
  41. }
  42. }
  43. $client = new Predis\Client($single_server);
  44. $client->getProfile()->defineCommand('increxby', 'IncrementExistingKeysBy');
  45. $client->mset('foo', 10, 'foobar', 100);
  46. var_export($client->increxby('foo', 'foofoo', 'foobar', 50));
  47. /*
  48. array (
  49. 0 => 60,
  50. 1 => NULL,
  51. 2 => 150,
  52. )
  53. */