minicli/curly

简单的Curl客户端

0.2.2 2022-10-07 07:40 UTC

This package is auto-updated.

Last update: 2024-09-01 01:43:34 UTC


README

一个为Minicli(但也可以独立使用)构建的实验性Curl客户端。

要求

需要 curlphp-curl

安装

要将Curly包含到您的应用程序中,首先使用Composer要求依赖项

composer require minicli/curly

用法

使用 Minicli/Curl/Client 类分别使用 get()post() 方法来执行GET和POST请求。

以下示例查询DEV API并获取用户的最新帖子

$crawler = new Client();

$articles_response = $crawler->get('https://dev.to/api/articles?username=erikaheidi');

if ($articles_response['code'] !== 200) {
    $app->getPrinter->error('Error while contacting the dev.to API.');
    return 1;
}

$articles = json_decode($articles_response['body'], true);
print_r($articles);

以下单命令Minicli应用程序将使用Curly从DEV.to获取用户的最新统计数据(需要 minicli/minicli

#!/usr/bin/env php
<?php
if (php_sapi_name() !== 'cli') {
    exit;
}

require __DIR__ . '/vendor/autoload.php';

use Minicli\App;
use Minicli\Exception\CommandNotFoundException;
use Minicli\Curly\Client;

$app = new App([
    'debug' => true,
    'theme' => '\Unicorn'
]);

$app->registerCommand('devto', function () use ($app) {
    $app->getPrinter()->display('Fetching from DEV...');
    $crawler = new Client();

    $articles_response = $crawler->get('https://dev.to/api/articles?username=DEVUSERNAME');

    if ($articles_response['code'] !== 200) {
        $app->getPrinter->error('Error while contacting the dev.to API.');
        return 1;
    }

    $articles = json_decode($articles_response['body'], true);
    $table[] = ['Title', 'Reactions'];
    foreach($articles as $article) {
        $table[] = [$article['title'], $article['positive_reactions_count']];
    }
    $app->getPrinter()->printTable($table);
    return 0;
});

try {
    $app->runCommand($argv);
} catch (CommandNotFoundException $notFoundException) {
    $app->getPrinter()->error("Command Not Found.");
    return 1;
}

return 0;