lua_scripting_abstraction.php 1.5 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 __DIR__.'/shared.php';
  11. // This example will not work with versions of Redis < 2.6.
  12. //
  13. // Additionally to the EVAL command, the Predis\Command\ScriptCommand class can
  14. // be used to leverage an higher level abstraction for Lua scripting that makes
  15. // scripts appear just like any other command on the client-side. This is basic
  16. // example on how a script-based INCREX command can be defined:
  17. use Predis\Command\ScriptCommand;
  18. class IncrementExistingKeysBy extends ScriptCommand
  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 <<<LUA
  29. local cmd, insert = redis.call, table.insert
  30. local increment, results = ARGV[1], { }
  31. for idx, key in ipairs(KEYS) do
  32. if cmd('exists', key) == 1 then
  33. insert(results, idx, cmd('incrby', key, increment))
  34. else
  35. insert(results, idx, false)
  36. end
  37. end
  38. return results
  39. LUA;
  40. }
  41. }
  42. $client = new Predis\Client($single_server, array(
  43. 'commands' => array(
  44. 'increxby' => 'IncrementExistingKeysBy',
  45. ),
  46. ));
  47. $client->mset('foo', 10, 'foobar', 100);
  48. var_export($client->increxby('foo', 'foofoo', 'foobar', 50));
  49. /*
  50. array (
  51. 0 => 60,
  52. 1 => NULL,
  53. 2 => 150,
  54. )
  55. */