PHP code example of allyson / laravel-http-service

1. Go to this page and download the library: Download allyson/laravel-http-service 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/ */

    

allyson / laravel-http-service example snippets


use ThreeRN\HttpService\Facades\HttpService;

// Requisição GET
$response = HttpService::get('https://api.example.com/users');
$users = $response->json();

// Requisição POST
$response = HttpService::post('https://api.example.com/users', [
    'name' => 'John Doe',
    'email' => '[email protected]'
]);

// Com headers customizados
$response = HttpService::post(
    'https://api.example.com/data',
    ['key' => 'value'],
    ['Authorization' => 'Bearer token123']
);

// GET com query parameters
HttpService::get($url, $query = [], $headers = []);

// POST com dados
HttpService::post($url, $data = [], $headers = []);

// PUT para atualização completa
HttpService::put($url, $data = [], $headers = []);

// PATCH para atualização parcial
HttpService::patch($url, $data = [], $headers = []);

// DELETE
HttpService::delete($url, $data = [], $headers = []);

// Desabilitar logging temporariamente
HttpService::withoutLogging()->get($url);

// Habilitar logging explicitamente
HttpService::withLogging()->post($url, $data);

// Desabilitar verificação de rate limit
HttpService::withoutRateLimit()->get($url);

// Timeout customizado (em segundos)
HttpService::timeout(60)->get($url);

// Encadear múltiplas opções
HttpService::withoutLogging()
    ->withoutRateLimit()
    ->timeout(30)
    ->get($url);

// Cache usando campo de data/hora
// Resposta: {"token": "abc123", "expirationTime": "2025-12-17 13:02:14"}
$response = HttpService::cacheUsingExpires('expirationTime')
    ->expiresAsDatetime()  // Padrão, pode ser omitido
    ->get('https://api.example.com/auth/token');

// Cache usando campo aninhado
// Resposta: {"data": {"auth": {"expires": "2025-12-17 15:30:00"}}}
$response = HttpService::cacheUsingExpires('data.auth.expires')
    ->expiresAsDatetime()
    ->post('https://api.example.com/login', $credentials);

// Cache usando segundos
// Resposta: {"token": "xyz789", "expires_in": 3600}
$response = HttpService::cacheUsingExpires('expires_in')
    ->expiresAsSeconds()
    ->get('https://api.example.com/token');

// Cache usando minutos
// Resposta: {"session_id": "sess_123", "ttl": 30}
$response = HttpService::cacheUsingExpires('ttl')
    ->expiresAsMinutes()
    ->get('https://api.example.com/session');

// Se 'expirationTime' não existir, cacheia por 2 horas (7200 segundos)
$response = HttpService::cacheUsingExpires('expirationTime', 7200)
    ->expiresAsDatetime()
    ->get('https://api.example.com/data');

// Cache por 1 hora (3600 segundos)
$response = HttpService::withCache(3600)
    ->get('https://api.example.com/data');

// Cache após 3 chamadas em 60 segundos, com TTL de 1 hora
$response = HttpService::cacheWhen(3, 60, 3600)
    ->get('https://api.example.com/data');

// Desabilitar cache para uma requisição específica
$response = HttpService::withoutCache()
    ->get('https://api.example.com/data');

// Limpar todo o cache de requisições
HttpService::clearCache();

// Cachear SOMENTE respostas 200 por 10 minutos
$response = HttpService::cacheOnly([200], 600)
        ->get('https://api.example.com/data');

// Cachear respostas 200 e 201 (com TTL customizado)
$response = HttpService::cacheOnly([200, 201], 300)
        ->post('https://api.example.com/create', $payload);

// Cachear tudo exceto erro 500
$response = HttpService::cacheExcept([500])
        ->get('https://api.example.com/data');

// Cachear tudo exceto 4xx e 5xx (exemplo)
$response = HttpService::cacheExcept([400,401,403,404,500,502,503], 3600)
        ->get('https://api.example.com/data');

use ThreeRN\HttpService\Exceptions\RateLimitException;

try {
    $response = HttpService::get('https://api.example.com/data');
} catch (RateLimitException $e) {
    echo "Domínio bloqueado: " . $e->getDomain();
    echo "Aguarde: " . $e->getRemainingMinutes() . " minutos";
}

// Aguarda o bloqueio expirar e então executa
$response = HttpService::waitOnRateLimit()->get('https://api.example.com/data');

// Lança RateLimitException normalmente, ignorando a config global
$response = HttpService::throwOnRateLimit()->get('https://api.example.com/data');

use ThreeRN\HttpService\Models\RateLimitControl;

// Verificar se está bloqueado
$isBlocked = RateLimitControl::isBlocked('api.example.com');

// Tempo restante de bloqueio (em minutos)
$minutes = RateLimitControl::getRemainingBlockTime('api.example.com');

// Tempo restante de bloqueio (em segundos)
$seconds = RateLimitControl::getRemainingBlockSeconds('api.example.com');

// Bloquear manualmente por 30 minutos
RateLimitControl::blockDomain('api.example.com', 30);

// Bloquear com motivo registrado
RateLimitControl::blockDomain('api.example.com', 30);
// (defina 'reason' via create/update direto no model se necessário)

// Desbloquear manualmente
RateLimitControl::unblockDomain('api.example.com');

// Listar bloqueios ativos
$blocks = RateLimitControl::active()->get();

// Limpar bloqueios expirados
$count = RateLimitControl::cleanExpiredBlocks();

// Parâmetros: threshold de falhas, tempo de recuperação em segundos, statuses de falha
$response = HttpService::withCircuitBreaker(5, 60)
    ->get('https://api.example.com/data');

// Customizando statuses que contam como falha (padrão: 500-599)
$response = HttpService::withCircuitBreaker(3, 30, [500, 502, 503, 504])
    ->post('https://api.example.com/data', $payload);

// Desabilitando pontualmente (quando habilitado globalmente)
$response = HttpService::withoutCircuitBreaker()
    ->get('https://api.example.com/health');

use ThreeRN\HttpService\Exceptions\CircuitBreakerException;

try {
    $response = HttpService::withCircuitBreaker()->get('https://api.example.com/data');
} catch (CircuitBreakerException $e) {
    echo "Circuito aberto para: " . $e->getDomain();
    echo "Tente novamente em: " . $e->getRemainingSeconds() . " segundos";
}

// Ativa por chamada — aguarda o circuito recuperar e re-tenta
$response = HttpService::withCircuitBreaker(3, 10)
    ->waitOnCircuitBreaker()
    ->get('https://api.example.com/data');

// Desativa pontualmente (quando a config global estiver habilitada)
$response = HttpService::throwOnCircuitBreaker()
    ->get('https://api.example.com/data');

use ThreeRN\HttpService\Models\HttpRequestLog;

// Buscar por URL
$logs = HttpRequestLog::byUrl('api.example.com')->get();

// Buscar por método HTTP
$posts = HttpRequestLog::byMethod('POST')->get();

// Buscar por status code
$errors = HttpRequestLog::byStatusCode(500)->get();

// Requisições com erro
$withErrors = HttpRequestLog::withErrors()->get();

// Requisições bem-sucedidas (2xx)
$successful = HttpRequestLog::successful()->get();

// Últimas 24 horas
$recent = HttpRequestLog::where('created_at', '>=', now()->subDay())
    ->orderBy('created_at', 'desc')
    ->get();

// Requisições lentas (mais de 5 segundos)
$slow = HttpRequestLog::where('response_time', '>', 5)->get();

return [
    // Habilitar logging de requisições
    'logging_enabled' => env('HTTP_SERVICE_LOGGING_ENABLED', true),
    
    // Habilitar controle de rate limiting
    'rate_limit_enabled' => env('HTTP_SERVICE_RATE_LIMIT_ENABLED', true),
    
    // Tempo de bloqueio padrão após 429 (minutos)
    'default_block_time' => env('HTTP_SERVICE_DEFAULT_BLOCK_TIME', 15),

    // Aguardar o bloqueio expirar em vez de lançar exceção (wait-on-rate-limit)
    'rate_limit_wait_on_block' => env('HTTP_SERVICE_RATE_LIMIT_WAIT_ON_BLOCK', false),
    
    // Timeout padrão de requisições (segundos)
    'timeout' => env('HTTP_SERVICE_TIMEOUT', 30),
    
    // Limpeza automática de bloqueios expirados
    'auto_clean_expired_blocks' => env('HTTP_SERVICE_AUTO_CLEAN_EXPIRED', true),
    
    // Retenção de logs (dias) - null para manter indefinidamente
    'log_retention_days' => env('HTTP_SERVICE_LOG_RETENTION_DAYS', 30),

    // Conexão de banco para gravação de logs (null = conexão padrão)
    'logging_connection' => env('HTTP_SERVICE_LOGGING_CONNECTION', null),

    // Conexão de banco para rate limiting (null = usa logging_connection ou padrão)
    'ratelimit_connection' => env('HTTP_SERVICE_RATELIMIT_CONNECTION', null),

    // Nome customizado da tabela de logs (null = 'http_request_logs')
    'logging_table' => env('HTTP_SERVICE_LOGGING_TABLE', null),

    // Nome customizado da tabela de rate limit (null = 'rate_limit_controls')
    'ratelimit_table' => env('HTTP_SERVICE_RATELIMIT_TABLE', null),

    // Circuit Breaker
    'circuit_breaker_enabled'         => env('HTTP_SERVICE_CIRCUIT_BREAKER_ENABLED', false),
    'circuit_breaker_threshold'       => env('HTTP_SERVICE_CIRCUIT_BREAKER_THRESHOLD', 5),
    'circuit_breaker_recovery_time'   => env('HTTP_SERVICE_CIRCUIT_BREAKER_RECOVERY_TIME', 60),
    'circuit_breaker_failure_statuses'=> range(500, 599), // não configurável via env
    'circuit_breaker_namespace'       => env('HTTP_SERVICE_CB_NAMESPACE', null),

    // Aguardar recuperação do circuito em vez de lançar exceção (wait-on-circuit-breaker)
    'circuit_breaker_wait_on_open'    => env('HTTP_SERVICE_CIRCUIT_BREAKER_WAIT_ON_OPEN', false),
];

namespace App\Http\Controllers;

use ThreeRN\HttpService\Facades\HttpService;
use ThreeRN\HttpService\Exceptions\RateLimitException;

class ApiController extends Controller
{
    public function fetchData()
    {
        try {
            $response = HttpService::get('https://api.example.com/data');
            
            return response()->json([
                'success' => true,
                'data' => $response->json(),
            ]);
        } catch (RateLimitException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Rate limited',
                'retry_in_minutes' => $e->getRemainingMinutes(),
            ], 429);
        }
    }
}

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use ThreeRN\HttpService\Facades\HttpService;
use ThreeRN\HttpService\Exceptions\RateLimitException;

class ProcessApiDataJob implements ShouldQueue
{
    public function handle()
    {
        try {
            $response = HttpService::post('https://api.example.com/process', $this->data);
            // Processar resposta...
        } catch (RateLimitException $e) {
            // Reagendar job para quando o bloqueio expirar
            $this->release($e->getRemainingMinutes() * 60);
        }
    }
}

function makeApiRequestWithRetry($url, $data, $maxRetries = 3)
{
    $attempt = 0;
    
    while ($attempt < $maxRetries) {
        try {
            $response = HttpService::timeout(30)->post($url, $data);
            
            if ($response->successful()) {
                return $response->json();
            }
            
        } catch (RateLimitException $e) {
            $waitMinutes = $e->getRemainingMinutes();
            sleep($waitMinutes * 60);
        } catch (\Exception $e) {
            sleep(5); // Aguarda antes de tentar novamente
        }
        
        $attempt++;
    }
    
    throw new \Exception("Falha após {$maxRetries} tentativas");
}

protected function schedule(Schedule $schedule)
{
    // Limpar bloqueios expirados diariamente
    $schedule->command('http-service:clean-blocks')->daily();
    
    // Limpar logs antigos semanalmente
    $schedule->command('http-service:clean-logs')->weekly();
}
bash
php artisan http-service:install
bash
php artisan migrate
bash
# Listar domínios bloqueados
php artisan http-service:list-blocks

# Desbloquear domínio específico
php artisan http-service:unblock api.example.com

# Limpar bloqueios expirados
php artisan http-service:clean-blocks
bash
# Limpar logs antigos (usa log_retention_days do config)
php artisan http-service:clean-logs

# Limpar logs com período customizado
php artisan http-service:clean-logs --days=7

http-service/
├── config/
│   └── http-service.php
├── database/
│   └── migrations/
├── src/
│   ├── Console/
│   │   └── Commands/
│   ├── Exceptions/
│   ├── Facades/
│   ├── Models/
│   ├── Services/
│   └── HttpServiceProvider.php
├── examples/
└── README.md