The Memcached::add() function is an inbuilt function of memcached class in PHP which is used to add a server to the server pool. It adds the specified server to the server pool. No connection is established to the server at this time, but if you are using consistent key distribution option (via Memcached::DISTRIBUTION_CONSISTENT or Memcached::OPT_LIBKETAMA_COMPATIBLE), some of the internal data structures will have to be updated. Thus, if you need to add multiple servers, it is better to use Memcached::addServers() as the update then happens only once.
The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.
Syntax:
public Memcached::addServer( $host, $port, $weight = 0): bool
Parameters: This function accepts three parameters that are:
- host: The hostname of the memcache server.
- port: The port on which memcache is running. Usually, this is 11211.
- weight: The weight of the server relative to the total weight of all the servers in the pool. Used for Load balancing.
Return Values: It returns true on success or false on failure.
Below program illustrate the Memcached::addServer() function in PHP:
Example 1:
PHP
<?php echo "<pre>" ; // Server & port details $server = '127.0.0.1' ; $port = 11211; // Initiate a new object of memcache $memcacheD = new Memcached(); // Add server if ( $memcacheD ->addServer( $server , $port )) { echo "** server added ** \n" ; } else { echo "** issue while creating a server **\n" ; } // Get server detail echo "Server Details :: \n" ; var_dump( $memcacheD ->getServerList()); ?> |
Output:
** server added **
Server Details :: array(1) {
[0]=>array(3) {
[“host”]=>string(9) “127.0.0.1”
[“port”]=>int(11211)
[“type”]=>string(3) “TCP”
}
}
Example 2 (error while creating server : already used port):
PHP
<?php echo "<pre>" ; // Server & port details $server = '127.0.0.1' ; $port = "8000" ; // Initiate a new object of memcache $memcacheD = new Memcached(); // Add server if ( $memcacheD ->addServer( $server , $port )) { echo "** server added ** \n" ; } else { echo "** issue while creating a server **\n" ; } // Get server detail echo "Server Details :: \n" ; var_dump( $memcacheD ->getServerList()); ?> |
Output:
** server added **
*** issue while creating a server **
Server Details ::
Reference: https://www.php.net/manual/en/memcached.addserver.php