MemcachedConnector.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Illuminate\Cache;
  3. use Memcached;
  4. class MemcachedConnector
  5. {
  6. /**
  7. * Create a new Memcached connection.
  8. *
  9. * @param array $servers
  10. * @param string|null $connectionId
  11. * @param array $options
  12. * @param array $credentials
  13. * @return \Memcached
  14. */
  15. public function connect(array $servers, $connectionId = null, array $options = [], array $credentials = [])
  16. {
  17. $memcached = $this->getMemcached(
  18. $connectionId, $credentials, $options
  19. );
  20. if (! $memcached->getServerList()) {
  21. // For each server in the array, we'll just extract the configuration and add
  22. // the server to the Memcached connection. Once we have added all of these
  23. // servers we'll verify the connection is successful and return it back.
  24. foreach ($servers as $server) {
  25. $memcached->addServer(
  26. $server['host'], $server['port'], $server['weight']
  27. );
  28. }
  29. }
  30. return $memcached;
  31. }
  32. /**
  33. * Get a new Memcached instance.
  34. *
  35. * @param string|null $connectionId
  36. * @param array $credentials
  37. * @param array $options
  38. * @return \Memcached
  39. */
  40. protected function getMemcached($connectionId, array $credentials, array $options)
  41. {
  42. $memcached = $this->createMemcachedInstance($connectionId);
  43. if (count($credentials) === 2) {
  44. $this->setCredentials($memcached, $credentials);
  45. }
  46. if (count($options)) {
  47. $memcached->setOptions($options);
  48. }
  49. return $memcached;
  50. }
  51. /**
  52. * Create the Memcached instance.
  53. *
  54. * @param string|null $connectionId
  55. * @return \Memcached
  56. */
  57. protected function createMemcachedInstance($connectionId)
  58. {
  59. return empty($connectionId) ? new Memcached : new Memcached($connectionId);
  60. }
  61. /**
  62. * Set the SASL credentials on the Memcached connection.
  63. *
  64. * @param \Memcached $memcached
  65. * @param array $credentials
  66. * @return void
  67. */
  68. protected function setCredentials($memcached, $credentials)
  69. {
  70. list($username, $password) = $credentials;
  71. $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
  72. $memcached->setSaslAuthData($username, $password);
  73. }
  74. }