xwp/wait-for

此包的最新版本(0.0.2)没有提供许可证信息。

0.0.2 2023-11-27 14:41 UTC

This package is auto-updated.

Last update: 2024-08-27 16:09:09 UTC


README

等待TCP连接到服务,带有超时时间。当等待需要一段时间才能启动的服务(如MySQL)上的Docker容器中的服务时很有用。

使用方法

将此库作为项目的开发依赖项要求

composer require --dev xwp/wait-for

在项目中使用它等待来自 localhost:3306 的TCP响应

// Include the Composer autoloader.
require_once __DIR__ . '/vendor/autoload.php';

$connection = new XWP\Wait_For\Tcp_Connection( 'localhost', 3306 );

try {
	$connection->connect( 30 );
} catch ( Exception $e ) {
	trigger_error( $e->getMessage(), E_USER_ERROR );
}

其中 localhost 是主机名,3306 是端口号,30 是超时时间(秒)。

设计决策

  • 在连接错误上使用PHP异常,以确保依赖于进程返回码的应用程序了解连接错误。

示例

使用提供的辅助程序来创建自己的等待逻辑

use XWP\Wait_For\With_Retry;

$runner = new With_Retry(
	function() {
		// Do something here.
		return false;
	}
);

if ( ! $runner->run( 10 ) ) {
	trigger_error( 'Failed to connect!' );
}