1414use function str_ends_with ;
1515
1616class PHPMem {
17- public const VERSION = '2.0.0 ' ;
17+ public const VERSION = '2.0.1 ' ;
18+
19+ /**
20+ * @var resource|null
21+ */
22+ private $ stream ;
1823
1924 /**
2025 * @param array<string, int|string> $server
@@ -279,6 +284,36 @@ public function version(): string {
279284 return str_replace ('VERSION ' , '' , $ this ->runCommand ('version ' ));
280285 }
281286
287+ /**
288+ * @throws MemcachedException
289+ */
290+ private function connect (): void {
291+ if (is_resource ($ this ->stream )) {
292+ return ; // Already connected
293+ }
294+
295+ $ address = isset ($ this ->server ['path ' ]) ? 'unix:// ' .$ this ->server ['path ' ] : 'tcp:// ' .$ this ->server ['host ' ].': ' .$ this ->server ['port ' ];
296+ $ stream = @stream_socket_client ($ address , $ error_code , $ error_message , 0.5 );
297+
298+ if ($ stream === false ) {
299+ throw new MemcachedException ('Could not connect: ' .$ error_code .' - ' .$ error_message );
300+ }
301+
302+ stream_set_timeout ($ stream , 1 );
303+ $ this ->stream = $ stream ;
304+ }
305+
306+ public function __destruct () {
307+ $ this ->disconnect ();
308+ }
309+
310+ public function disconnect (): void {
311+ if (is_resource ($ this ->stream )) {
312+ fclose ($ this ->stream );
313+ $ this ->stream = null ;
314+ }
315+ }
316+
282317 /**
283318 * Run command.
284319 *
@@ -335,20 +370,19 @@ public function runCommand(string $command): string {
335370 * @throws MemcachedException
336371 */
337372 private function streamConnection (string $ command , string $ command_name ): string {
338- $ address = isset ($ this ->server ['path ' ]) ? 'unix:// ' .$ this ->server ['path ' ] : 'tcp:// ' .$ this ->server ['host ' ].': ' .$ this ->server ['port ' ];
339- $ stream = @stream_socket_client ($ address , $ error_code , $ error_message , 0.5 );
373+ $ this ->connect ();
340374
341- if ($ stream === false ) {
342- throw new MemcachedException ('Command: " ' .$ command .'": ' .$ error_code .' - ' .$ error_message );
375+ if (!is_resource ($ this ->stream ) || feof ($ this ->stream )) {
376+ $ this ->disconnect ();
377+ $ this ->connect ();
343378 }
344379
345- stream_set_timeout ($ stream , 1 );
346- fwrite ($ stream , $ command );
380+ fwrite ($ this ->stream , $ command );
347381
348382 $ buffer = '' ;
349383
350- while (!feof ($ stream )) {
351- $ line = fgets ($ stream , 4096 );
384+ while (!feof ($ this -> stream )) {
385+ $ line = fgets ($ this -> stream , 4096 );
352386
353387 if ($ line === false ) {
354388 break ;
@@ -370,8 +404,6 @@ private function streamConnection(string $command, string $command_name): string
370404 }
371405 }
372406
373- fclose ($ stream );
374-
375407 return $ buffer ;
376408 }
377409
0 commit comments