20 Awesome PHP Libraries For Early 2017

This week we have for you a collection of high-quality PHP libraries that have caught our eye in the last couple of months. We've tried our best to include projects that are active, well documented, and will have a realistic shot at finding a place in your developer's workbelt.

If we've haven't included your favorite new library, feel free to share it in the comments :)


Requests for PHP

A no-dependencies library that lets you send HTTP requests. It provides the needed methods for adding headers, accessing response data, handling forms, and everything else you may need, neatly packaged in a clean and easy to use API.

$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);
// int(200)

var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"

var_dump($request->body);
// string(26891) "[...]"

Rinvex Country

Rinvex Country is a PHP package that lets developers retrieve detailed information about the countries of the world. Using the over 50 methods you can get the area of Angola, the currency of Cyprus, the native name of Namibia or even the FIFA name of Finland. There is a ton of info available and the data sources are pretty reliable.

$egypt = country('eg');

$egypt->getCapital();   // Cairo
$egypt->getDemonym();   // Egyptian
$egypt->getTld();       // .eg
$egypt->getContinent(); // Africa
$egypt->getSubregion(); // Northern Africa
$egypt->getBorders();   // ["ISR","LBY","SDN"]

Botman

A PHP library for developing messenger bots. Works with most of the popular messaging platforms including Facebook Messenger, Slack, Telegram, WeChat, and others. There is also a helpful boilerplate Laravel project available here.

// create an instance
$botman = BotManFactory::create($config);

// give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot) {
    $bot->reply('Hello yourself.');
});

// start listening
$botman->listen();

If you are not familiar with the concept of messenger bots we suggest you check out our article Developer's Introduction To Chatbots.


Charts

Laravel package for generating highly customizable charts out of datasets. The package works as a PHP wrapper for multiple built-in JavaScript chart libraries, allowing devs to create a wide variety of graphs, gauges and progressbars using only one tool.

$chart = Charts::create('line', 'highcharts')
 ->title('My nice chart')
 ->labels(['First', 'Second', 'Third'])
 ->values([5,10,20])
 ->dimensions(0,500);

Swap

Swap allows you to retrieve currency exchange rates from a number of services such as Fixer, Google, and Yahoo. Request responses can be easily cached and accessed later. The library is available in the form of a Laravel Package as well.

// Build Swap with Fixer.io
$swap = (new Builder())
    ->add('fixer')
    ->build();

// Get the latest EUR/USD rate
$rate = $swap->latest('EUR/USD');

// 1.129
$rate->getValue();

// Get the EUR/USD rate 15 days ago
$rate = $swap->historical('EUR/USD', (new \DateTime())->modify('-15 days'));

Math PHP

A collection of mathematical functions and algorithms ranging from simple algebra to finances, statistics, numerical analysis and others fields. The library is modular, has a straightforward API, and doesn't require any external dependencies.

// Factors of an integer
$factors = Algebra::factors($n);

// Fibonacci sequence
$fib = Advanced::fibonacci($n);

// Combinations
$nCk  = Combinatorics::combinations($n, $k);

// Likelihood ratios
$LL = Experiment::likelihoodRatio($a, $b, $c, $d);

PHPUnit

PHPUnit is an advanced testing framework that enables teams to thoroughly test their code. Unit tests are written in standalone object-oriented classes with the help of many methods for handling assertions, dependencies, etc. A simple CLI is provided for running test and generating reports.

class StackTest extends TestCase
{
    public function testPushAndPop()
    {
        $stack = [];
        $this->assertEquals(0, count($stack));

        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));

        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}

Atoum

A less popular testing framework we also wanted to share. Atoum offers a one-step installation precess and a relatively simple workflow, while still maintaining a ton of great features. It has a mock engine, expressive assertions, and a CLI that can execute multiple tests in parallel.

$this->given($testedInstance = new testedClass())
    ->and($testedClass[] = $firstValue = uniqid())
    ->then
        ->sizeof($testedInstance)->isEqualTo(1)
        ->string($testedClass[0])->isEqualTo($firstValue);

Simple Regex Language

A PHP implementation of the Simple Regex Language - a verbose way of writing regular expressions. The library provides multiple methods that can be chained together, forming readable and easy to understand RegEx rules. The library has ports for JavaScript and Python as well.

$query = SRL::startsWith()
    ->anyOf(function (Builder $query) {
        $query->digit()
            ->letter()
            ->oneOf('._%+-');
    })->onceOrMore()
    ->literally('@')
    ->anyOf(function (Builder $query) {
        $query->digit()
            ->letter()
            ->oneOf('.-');
    })->onceOrMore()
    ->literally('.')
    ->letter()->atLeast(2)
    ->mustEnd()->caseInsensitive();

Stash

Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain actions, like database queries or calls to external APIs, take a lot of time to run but tend to have the same results over short periods of time. This makes it much more efficient to store the results and call them back up later.

$pool = $this->cachePool;

// Get a Stash object from the cache pool.
$item = $pool->getItem("/user/{$userId}/info");

// Get the data from it, if any happens to be there.
$userInfo = $item->get();

// Check to see if the cache missed, which could mean that it either
// didn't exist or was stale.
if($item->isMiss())
{
    // Run the relatively expensive code.
    $userInfo = loadUserInfoFromDatabase($userId);

    // Set the new value in $item.
    $item->set($userInfo);

    // Store the expensive code so the next time it doesn't miss.
    $pool->save($item)
}

PHP VCR

A port of the popular Ruby library for testing HTTP interactions. PHP VCR records HTTP requests and stores them in "cassettes" which can be replayed later on. A set of testing utilities are also provided, making it possible to inspect and compare recordings in detail.

// After turning on, the VCR will intercept all requests
\VCR\VCR::turnOn();

// Record requests and responses in cassette file 'example'
\VCR\VCR::insertCassette('example');

// Following request will be recorded once and replayed in future test runs
$result = file_get_contents('http://example.com');
$this->assertNotEmpty($result);

// To stop recording requests, eject the cassette
\VCR\VCR::eject();

// Turn off VCR to stop intercepting requests
\VCR\VCR::turnOff();

OAuth 2.0 Server

This library allows you to easily configure an OAuth 2.0 server and set up all the authentication levels needed to protect your API. It is fully standards compliant and supports all the grants defined by OAuth protocol. The Laravel Passport module is built on top of the OAuth 2.0 Server.

// Setup the authorization server
$server = new \League\OAuth2\Server\AuthorizationServer(
    $clientRepository,
    $accessTokenRepository,
    $scopeRepository,
    $privateKey,
    $publicKey
);

// Enable a grant on the server
$server->enableGrantType(
    new \League\OAuth2\Server\Grant\ClientCredentialsGrant(),
    new \DateInterval('PT1H') // access tokens will expire after 1 hour
);

Imagine

An image manipulation library that tries to bring together all low level PHP image processing libraries under the same object-oriented API. This allows Imagine to be used for a wide variety of tasks such as drawing, resizing, cropping, filters, effects, metadata editing, and others.

$palette = new Imagine\Image\Palette\RGB();

$image = $imagine->create(new Box(400, 300), $palette->color('#000'));

$image->draw()
    ->ellipse(new Point(200, 150), new Box(300, 225), $image->palette()->color('fff'));

$image->save('/path/to/ellipse.png');

MINI

Extremely simple and easy to understand skeleton PHP application, providing only the most essential features every project needs. It does not strive to be a do-it-all framework like Laravel, but due to it's simplicity MINI can be used for getting smaller apps up and running in no time.

// Working with the model
$songs = $this->model->getAllSongs();
$amount_of_songs = $this->model->getAmountOfSongs();

// Loading views
require APP . 'views/_templates/header.php';
require APP . 'views/songs/index.php';
require APP . 'views/_templates/footer.php';

AWS SDK

The official PHP library for working with Amazon Web Services. The SDK makes it easy to connect AWS with any PHP project and access all the various available services. There is also a useful Laravel wrapper which can be found here.

// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-west-2'
]);

$s3->putObject([
    'Bucket' => 'my-bucket',
    'Key'    => 'my-object',
    'Body'   => fopen('/path/to/file', 'r'),
    'ACL'    => 'public-read',
]);

Purl

Lightweight PHP library for working with URLs. With Purl you can compose complex paths attribute by attribute, extract data from URLs, manipulate queries, recognize URLs in strings, and much more.

$url = \Purl\Url::parse('http://jwage.com')
    ->set('scheme', 'https')
    ->set('port', '443')
    ->set('user', 'jwage')
    ->set('pass', 'password')
    ->set('path', 'about/me')
    ->set('query', 'param1=value1&param2=value2');

echo $url->getUrl(); // https://jwage:[email protected]:443/about/me?param1=value1&param2=value2
echo $url->publicSuffix; // com
echo $url->registerableDomain; // jwage.com

Daux.io

Documentation generator that uses a simple folder structure and Markdown files to create responsive documentation websites. Daux.io has automatic syntax highlighting, 4 theming options, Bootstrap HTML for easy customization, navigation with readable URLs, and many other goodies.

// Example configuration
{
    "title": "DAUX.IO",
    "tagline": "The Easiest Way To Document Your Project",
    "author": "Justin Walsh",
    "image": "app.png",
    "html": {
        "theme": "daux-blue",
        "breadcrumbs": true,
        "repo": "justinwalsh/daux.io",
        "edit_on_github": "justinwalsh/daux.io/blob/master/docs",
        "twitter": ["justin_walsh", "todaymade"],
        "google_analytics": "UA-12653604-10",
        "links": {
            "Download": "https://github.com/justinwalsh/daux.io/archive/master.zip",
            "GitHub Repo": "https://github.com/justinwalsh/daux.io",
            "Made by Todaymade": "http://todaymade.com"
        }
    }
}

Dompdf

Dompdf is a PDF generator that takes regular HTML markup and converts it to .pdf files. It understands most CSS rules, which can be fed in-line or via an external stylesheet.

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();

Instaphp

Non-official library for accessing the Instagram API. It provides developers with an easy way to authenticate their app and get access to various Instagram data endpoints including images, users, likes, comments, and tags.

$api = new Instaphp\Instaphp([
    'client_id' => 'your client id',
    'client_secret' => 'your client secret',
    'redirect_uri' => 'http://somehost.foo/callback.php',
    'scope' => 'comments+likes'
]);

$popular = $api->Media->Popular(['count' => 10]);

if (empty($popular->error)) {
    foreach ($popular->data as $item) {
        printf('<img src="%s">', $item['images']['low_resolution']['url']);
    }
}

Latitude

Zero-dependencies library for building SQL queries using chainable methods. It supports most query types and works well with MySQL, Postgres, SQL Server, and other databases. There are also built-in escaping helpers for protecting against SQL injection.

$select = SelectQuery::make(
        'id',
        'username'
    )
    ->from('users');

echo $select->sql();
// SELECT id, username FROM users
Bootstrap Studio

The revolutionary web design tool for creating responsive websites and apps.

Learn more

Related Articles

Comments 6

  • The problem with Math PHP is that it requires PHP 7! Does anyone know another PHP math lib which accepts PHP 5.x? but i think best php resolution is to provide for in this site of http://edu.microdots.in/ its helpful for all doubts are clearly explained for this center.

  • I hate so much reg-expression. So I will check SimpleRegex.

Thanks!

Hello,

The problem with Math PHP is that it requires PHP 7 (Argh... can't we code a proper math library with PHP 5.x?)! Does anyone know another PHP math lib which accepts PHP 5.x?

My favorite php classes are

Thank you for Requests for PHP and Stash!

Ole-Martin Bratteng

Since you linked to Mini, you could've linked to Mini 2 and Mini 3 at the same time