PHP
Installing packages from Packagist
Learn to search for and install packages from Packagist.
What is Packagist?
Packagist is the main repository for PHP packages. Composer searches and downloads from here. A package name has the vendor/project form; for example monolog/monolog is a logging library, guzzlehttp/guzzle is an HTTP client.
When you run composer require monolog/monolog, Composer finds the package on Packagist, downloads it into vendor/ and adds it to the autoload. Afterwards you can import classes with use.
Using a package
After you install a package with composer require, calling require_once vendor/autoload.php makes its classes usable. For example with Monolog installed, write new Monolog\Logger("app") to create a logger.
With GuzzleHttp installed, send HTTP requests with new GuzzleHttp\Client(). Since the Composer autoloader loads namespaces automatically, you do not write file paths; use is enough.
Exercise Monolog Logger simulation
Mimic the Logger class of the Monolog package. Define namespace Monolog;; inside it add a Logger class. Add a public string $name property and public function __construct(string $name) that assigns $this->name = $name. public function info(string $msg): string should return "[" . $this->name . "] " . $msg.
Create an instance with $log = new \Monolog\Logger("app"), call info("Started") and print its output.
Show example solution
string { return "[" . $this->name . "] " . $msg; } }. Print with $log = new \Monolog\Logger("app"); echo $log->info("Started") . "\n";.
Example solution:
<?php
namespace Monolog;
class Logger {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function info(string $msg): string {
return "[" . $this->name . "] " . $msg;
}
}
$log = new \Monolog\Logger("app");
echo $log->info("Started") . "\n";
Test yourself
-
Complete the package name
<?php
// Monolog package name
$cfg = ["name" => "____"];
echo $cfg["name"] . "\n";
Show answer
<?php
// Monolog package name
$cfg = ["name" => "monolog/monolog"];
echo $cfg["name"] . "\n";
-
Match the Packagist concepts
- Packagist
- Package repository
- monolog/monolog
- Logging library
- guzzlehttp/guzzle
- HTTP client
- vendor/project
- Package name form
-
What does the guzzlehttp/guzzle package do?
- It sends HTTP requests
- It logs events
- It runs database queries
- It compresses files
Show answer
It sends HTTP requests — Correct. GuzzleHttp is an HTTP client library.
Next lesson: composer update and install