How To Use PHP Composer With A Basic PHP Example

Vitaliy Dotsenko
Legacybeta
Published in
2 min readJun 5, 2020
Photo by Brandable Box on Unsplash

In the last article we learned how to install Composer, today’s topic is using composer packages from the packagist repository in PHP.

We’re going to install Guzzle HTTP client and Monolog.

Guzzle HTTP client needs to create HTTP requests to HTTP API endpoints and we’ll use Monolog for logging results of requests.

Step 1

First of all, we need to create a folder for our project then move to this folder and install Guzzle via composer:

composer require guzzlehttp/guzzle

Step 2

Create the app.php file with the content:

<?phprequire_once __DIR__ . '/vendor/autoload.php';use GuzzleHttp\Client;$client = new Client();
$response = $client->request('GET', 'https://httpbin.org/get');
echo $response->getBody();

The above code creates HTTP GET request to test HTTP endpoint https://httpbin.org/get. The line require_once __DIR__ . '/vendor/autoload.php'; requires for using composer in your PHP code.

Then run app.php by the command php app.php you'll get an output like this:

{
"args": {},
"headers": {
"Host": "httpbin.org",
"User-Agent": "GuzzleHttp/6.5.3 curl/7.47.0 PHP/7.4.6",
"X-Amzn-Trace-Id": "Root=1-5ecba504-ca25bf248966f8da7aedd5d0"
},
"origin": "127.0.0.1",
"url": "https://httpbin.org/get"
}

Step 3

The last step is installing Monolog library:

composer require monolog/monolog

and modify the app.php a bit to support logging:

<?phpuse GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use GuzzleHttp\MessageFormatter;
require_once __DIR__ . '/vendor/autoload.php';$monologHandler = new Logger(
'Logger', [
new StreamHandler('./log.txt', Monolog\Logger::DEBUG)
]);
$stack = HandlerStack::create();
$stack->push(
Middleware::log(
$monologHandler,
new MessageFormatter('{res_body}')
)
);
$client = new Client(['handler' => $stack]);
$response = $client->request('GET', 'https://httpbin.org/get');
echo $response->getBody();

Now after run app.php you'll get log.txt in the project folder with Guzzle responses.

I hope with this example you have a good idea of how easy it is to add Composer to your existing PHP code. Perhaps, in the process, you learned a bit about Guzzle and Monolog too!

--

--

Vitaliy Dotsenko
Legacybeta

I like coding, open-source software and hi-tech 🚀