lua_scripting_abstraction.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 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 <<<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, array(
  44. 'profile' => function ($options) {
  45. $profile = $options->getDefault('profile');
  46. $profile->defineCommand('increxby', 'IncrementExistingKeysBy');
  47. return $profile;
  48. },
  49. ));
  50. $client->mset('foo', 10, 'foobar', 100);
  51. var_export($client->increxby('foo', 'foofoo', 'foobar', 50));
  52. /*
  53. array (
  54. 0 => 60,
  55. 1 => NULL,
  56. 2 => 150,
  57. )
  58. */