24 Awesome PHP Libraries Every Developer Should Know

This article presents a curated list of 24 essential PHP libraries, ranging from micro‑frameworks and routing tools to validation, benchmarking, and command‑line wrappers, each accompanied by concise descriptions and practical code examples for immediate use.

Art of Distributed System Architecture Design
Art of Distributed System Architecture Design
Art of Distributed System Architecture Design
24 Awesome PHP Libraries Every Developer Should Know

As a PHP developer, there are many useful libraries on GitHub; here are the 24 coolest ones, each with a brief description and example code.

1. Dispatch – Micro‑framework Dispatch is a small PHP framework without a full MVC setup, allowing you to define URL rules and methods for better organization of APIs, simple sites, or prototypes.

include 'dispatch.php';

get('/greet', function () {
    render('greet-form');
});

post('/greet', function () {
    $name = from($_POST, 'name');
    render('greet-show', array('name' => $name));
});

dispatch();

2. Klein – Fast PHP Router Klein is a lightweight routing library for PHP 5.3+, offering concise syntax and support for HTTP method constraints and regular‑expression routes.

respond('/[:name]', function ($request) {
    echo 'Hello ' . $request->name;
});

respond('GET', '/posts', $callback);
respond('POST', '/posts/create', $callback);
respond(array('POST','GET'), $route, $callback);

3. Ham – Cached Router Ham is a lightweight router that caches I/O using XCache or APC for faster performance.

require '../ham/ham.php';

$app = new Ham('example');
$app->config_from_file('settings.php');
$app->route('/pork', function($app) {
    return "Delicious pork.";
});

$hello = function($app, $name='world') {
    return $app->render('hello.html', array('name' => $name));
};
$app->route('/hello/<string>', $hello);
$app->run();

4. Assetic – Asset Management Assetic merges and minifies CSS/JS assets, reducing download size and HTTP requests.

use Assetic\Asset\AssetCollection;
use Assetic\Asset\FileAsset;
use Assetic\Asset\GlobAsset;

$js = new AssetCollection(array(
    new GlobAsset('/path/to/js/*'),
    new FileAsset('/path/to/another.js'),
));

echo $js->dump();

5. ImageWorkshop – Layered Image Manipulation ImageWorkshop lets you work with layered images, resize, crop, watermark, etc.

$norwayLayer = ImageWorkshop::initFromPath('/path/to/images/norway.jpg');
$watermarkLayer = ImageWorkshop::initFromPath('/path/to/images/watermark.png');
$image = $norwayLayer->getResult();
header('Content-type: image/jpeg');
imagejpeg($image, null, 95);
exit;

6. Snappy – Snapshot/PDF Generation Snappy generates snapshots, HTML, and PDFs via wkhtmltopdf.

require_once '/path/to/snappy/src/autoload.php';
use Knp\Snappy\Pdf;

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('http://www.github.com');

7. Idiorm – Lightweight ORM Idiorm provides a simple PDO‑based query builder and ORM.

$user = ORM::for_table('user')
    ->where_equal('username', 'j4mie')
    ->find_one();

$user->first_name = 'Jamie';
$user->save();

$tweets = ORM::for_table('tweet')
    ->select('tweet.*')
    ->join('user', array('user.id', '=', 'tweet.user_id'))
    ->where_equal('user.username', 'j4mie')
    ->find_many();

foreach ($tweets as $tweet) {
    echo $tweet->text;
}

8. Underscore – PHP Utility Belt A PHP port of Underscore.js offering functional helpers.

__::each(array(1, 2, 3), function($num) { echo $num . ','; });
$multiplier = 2;
__::each(array(1, 2, 3), function($num, $index) use ($multiplier) {
    echo $index . '=' . ($num * $multiplier) . ',';
});
__::reduce(array(1, 2, 3), function($memo, $num) { return $memo + $num; }, 0);
__::find(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; });
__::filter(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; });

9. Requests – Simple HTTP Requests A wrapper that simplifies making HTTP requests.

$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);
var_dump($request->status_code);
var_dump($request->headers['content-type']);
var_dump($request->body);

10. Buzz – Simple HTTP Client Another lightweight HTTP client library.

$request = new Buzz\Message\Request('HEAD', '/', 'http://google.com');
$response = new Buzz\Message\Response();
$client = new Buzz\Client\FileGetContents();
$client->send($request, $response);

echo $request;
echo $response;

11. Goutte – Web Scraping Goutte provides an elegant API for crawling and extracting data from web pages.

require_once '/path/to/goutte.phar';
use Goutte\Client;

$client = new Client();
$crawler = $client->request('GET', 'http://www.symfony-project.org/');
$link = $crawler->selectLink('Plugins')->link();
$crawler = $client->click($link);
$t = $crawler->filter('#data')->text();
echo "Here is the text: $t";

12. Carbon – DateTime Library Carbon extends PHP's DateTime with a fluent API.

printf("Right now is %s", Carbon::now()->toDateTimeString());
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);
if (Carbon::now()->gte($endOfWorld)) { die(); }
if (Carbon::now()->isWeekend()) { echo 'Party!'; }

13. Ubench – Micro Benchmarking Ubench measures execution time and memory usage of PHP code.

use Ubench\Ubench;
$bench = new Ubench;
$bench->start();
// ... code to benchmark ...
$bench->end();
echo $bench->getTime();
echo $bench->getMemoryPeak();

14. Validation – Input Validation Engine Respect\Validation offers a powerful, chainable validation library.

use Respect\Validation\Validator as v;
$number = 123;
v::numeric()->validate($number);
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate('alganet');
$user = new stdClass;
$user->name = 'Alexandre';
$user->birthdate = '1987-07-01';
$userValidator = v::attribute('name', v::string()->length(1,32))
    ->attribute('birthdate', v::date()->minimumAge(18));
$userValidator->validate($user);

15. Filterus – Filtering Library Filterus validates and filters strings according to defined patterns.

$f = Filter::factory('string,max:5');
$str = 'This is a test string';
$f->validate($str); // false
$f->filter($str); // 'This '

16. Faker – Fake Data Generator Faker creates realistic fake data for testing.

require_once '/path/to/Faker/src/autoload.php';
$faker = Faker\Factory::create();
echo $faker->name;
echo $faker->address;
echo $faker->text;

17. Mustache.php – Elegant Templating Mustache provides logic‑less templates for PHP.

$m = new Mustache_Engine;
echo $m->render('Hello {{planet}}', array('planet' => 'World!'));

18. Gaufrette – Filesystem Abstraction Gaufrette abstracts local files, FTP, S3, etc., behind a unified API.

use Gaufrette\Filesystem;
use Gaufrette\Adapter\Local as LocalAdapter;
$adapter = new LocalAdapter('/var/media');
$filesystem = new Filesystem($adapter);
$content = $filesystem->read('myFile');
$filesystem->write('myFile', 'Hello I am the new content');

19. Omnipay – Payment Processing Omnipay offers a consistent API for multiple payment gateways.

use Omnipay\GatewayFactory;
$gateway = GatewayFactory::create('Stripe');
$gateway->setApiKey('abc123');
$formData = ['number' => '4111111111111111', 'expiryMonth' => 6, 'expiryYear' => 2016];
$response = $gateway->purchase(['amount' => 1000, 'card' => $formData]);
if ($response->isSuccessful()) { print_r($response); }
elseif ($response->isRedirect()) { $response->redirect(); }
else { exit($response->getMessage()); }

20. Upload – File Upload Handling Upload simplifies file uploads with validation of type and size.

$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);
$file->addValidations(array(
    new \Upload\Validation\Mimetype('image/png'),
    new \Upload\Validation\Size('5M')
));
try { $file->upload(); } catch (\Exception $e) { $errors = $file->getErrors(); }

21. HTMLPurifier – HTML XSS Protection HTMLPurifier sanitizes HTML to prevent XSS attacks.

require_once '/path/to/HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

22. ColorJizz‑PHP – Color Manipulation ColorJizz converts between color formats and performs basic color operations.

use MischiefCollective\ColorJizz\Formats\Hex;
$red_hex = new Hex(0xFF0000);
$red_cmyk = $hex->toCMYK();
echo $red_cmyk; // 0,1,1,0
echo Hex::fromString('red')->hue(-20)->greyscale(); // 555555

23. PHP Geo – Geolocation Library PHP Geo calculates high‑precision distances between coordinates.

use Location\Coordinate;
use Location\Distance\Vincenty;
$coordinate1 = new Coordinate(19.820664, -155.468066);
$coordinate2 = new Coordinate(20.709722, -156.253333);
$calculator = new Vincenty();
$distance = $calculator->getDistance($coordinate1, $coordinate2);

24. ShellWrap – Elegant Command‑Line Wrapper ShellWrap lets you invoke powerful Linux/Unix commands from PHP.

require 'ShellWrap.php';
use \MrRio\ShellWrap as sh;

echo sh::ls();
sh::git('checkout', 'master');

echo sh::grep('html', sh::curl('http://example.com', array('location' => true)));
sh::touch('file.html');
sh::rm('file.html');
try { sh::rm('file.html'); } catch (Exception $e) { echo 'Caught failing sh::rm() call'; }

These libraries, sourced from the original tutorialzine article and translated by Jobbole, provide a solid toolbox for PHP developers to accelerate development, improve code quality, and handle common tasks efficiently.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPlibrariesopen-sourcephp-frameworksweb-development
Art of Distributed System Architecture Design
Written by

Art of Distributed System Architecture Design

Introductions to large-scale distributed system architectures; insights and knowledge sharing on large-scale internet system architecture; front-end web architecture overviews; practical tips and experiences with PHP, JavaScript, Erlang, C/C++ and other languages in large-scale internet system development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.