PHP code example of lgarret / health-check-bundle

1. Go to this page and download the library: Download lgarret/health-check-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lgarret / health-check-bundle example snippets


// config/bundles.php
return [
    // ...
    Lgarret\HealthCheckBundle\HealthCheckBundle::class => ['all' => true],
];



namespace App\Check;

use Lgarret\HealthCheckBundle\Check\HealthCheckInterface;
use Lgarret\HealthCheckBundle\Dto\HealthCheckResult;
use Doctrine\DBAL\Connection;

class DatabaseHealthCheck implements HealthCheckInterface
{
    public function __construct(private readonly Connection $connection)
    {
    }

    public function getName(): string
    {
        return 'database';
    }

    public function check(): HealthCheckResult
    {
        try {
            $this->connection->executeQuery('SELECT 1');
            return HealthCheckResult::ok();
        } catch (\Throwable $e) {
            return HealthCheckResult::ko($e->getMessage());
        }
    }
}

use Lgarret\HealthCheckBundle\Client\HealthCheckClient;

class StatusController
{
    public function __construct(private readonly HealthCheckClient $healthCheckClient)
    {
    }

    public function __invoke(): Response
    {
        $result = $this->healthCheckClient->check(
            url: 'https://other-site.example.com/health',
            secret: 'their-secret-token',
            header: 'X-Health-Token', // optional, defaults to "Authorization"
            timeout: 3.0,             // optional, defaults to 5 seconds
        );

        if (!$result->reachable) {
            // $result->error contains the network/parsing error (timeout, connection refused, invalid response, ...)
        }

        // $result->report is a HealthCheckReport (status + per-check HealthCheckResult), like the local one
    }
}