Monolog
With Monolog you can create advanced logging systems by sending your PHP logs to files, sockets, databases, inboxes or other web services. The library has over 50 handlers for various utilities and can be integrated into frameworks such as Laravel, Symfony2 and Slim.
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
// add records to the log
$log->warning('Foo');
$log->error('Bar');
PHPExcel
A set of PHP classes that allow developers to easily implement spreadsheet editing in their apps. The library can read and write spreadsheet documents in a number of popular formats including Excel (both .xls and .xlsx), OpenDocument (.ods), and CSV to name a few.
include 'PHPExcel/IOFactory.php';
$inputFileName = './sampleData/example1.xls';
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory';
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
PHP-ML
An interesting library for experimenting with Machine Learning, PHP-ML gives you an easy to use API for training your bot and making it do predictions based on input data. It offers a variety of different algorithms for pattern recognition and complex statistics calculations.
use Phpml\Classification\KNearestNeighbors;
$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);
$classifier->predict([3, 2]);
// returns 'b' as the [3, 2] point is closer to the points in group b
Opauth
Library for enabling users to authenticate themselves via their account in social networks or other services. Of course all the big names are available: Google, Facebook, Twitter, Github, Instagram, LinkedIn. Opauth is supported by many PHP frameworks so it can be easily integrated in most PHP apps.
'Strategy' => array(
// Define strategies here.
'Facebook' => array(
'app_id' => 'YOUR APP ID',
'app_secret' => 'YOUR APP SECRET'
),
);
Whoops
Whoops greatly improves the debugging experience in PHP by displaying a detailed error page when something breaks in an app. This error page gives us the full stack trace showing the specific files and snippets of code that caused the exception, all syntax-highlighted and colorful. The Laravel framework comes with Whoops built-in.
$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$whoops->register();
// That's it!
FastCache
Implementing this caching system in your PHP apps is guaranteed to make them load way quicker by reducing the amount of queries sent to the database. Instead of executing every DB query, FastCache sends only the unique ones, saves them as cache, and then serves them from there for each repetition. This way if you have the same query repeated 1000 times, it will be loaded from the DB one time, the rest 999 loads will be from cache.
use phpFastCache\CacheManager;
$config = array(
"storage" => "files",
"path" => "/your_cache_path/dir/",
);
CacheManager::setup($config);
// Try to get from Cache first with an Identity Keyword
$products = CacheManager::get("products");
// If not available get from DB and save in Cache.
if(is_null($products)) {
$products = "DB SELECT QUERY";
// Cache your $products for 600 seconds.
CacheManager::set($cache_keyword, $products,600);
}
Guzzle
Guzzle is one of the best HTTP clients out there. It can handle almost any HTTP task that you throw at it: synchronous and asynchronous requests, HTTP cookies, streaming of large uploads and downloads. Working with Guzzle is really easy and the docs are well written with lots of examples and detailed explanations.
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
Munee
Munee has lots of tricks up its sleeve: combining several CSS or JavaScript requests into one, image resizing, automatic compilation for Sass, Less and CoffeeScript files, as well as minification and Gzip compression. All of the previously mentioned processes are cached both server-side and client-side for optimal performance.
require 'vendor/autoload.php';
echo \Munee\Dispatcher::run(new \Munee\Request());
<!-- Combining two CSS files into one. -->
<link rel="stylesheet" href="/css/bootstrap.min.css, /css/demo.css">
<!-- Resizing image -->
<img src="/path/to/image.jpg?resize=width[100]height[100]exact[true]">
<!-- Files that need preprocessing are compiled automatically -->
<link rel="stylesheet" href="/css/demo.scss">
<!-- Minifying code -->
<script src="/js/script.js?minify=true"></script>
Twig
Templating engine with a very clean “mustache” syntax that makes markup shorter and easier to write. Twig offers everything you would expect from a modern templating library: variable escaping, loops, if/else blocks, as well as a secure sandbox mode for verifying template code.
// Template HTML
<p>Welcome {{ name }}!</p>
// Rendering
require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
'cache' => '/path/to/compilation_cache',
));
echo $twig->render('index.html', array('name' => 'George'));
Goutte
Goutte is a Web Scraper that can crawl websites and extract HTML or XML data from them. It works by sending a request to a given URL and returning a Crawler object, which allows the developer to interact with the remote page in various ways.
use Goutte\Client;
$client = new Client();
// Go to the symfony.com website
$crawler = $client->request('GET', 'http://www.symfony.com/blog/');
// Click on the links
$link = $crawler->selectLink('Security Advisories')->link();
$crawler = $client->click($link);
// Extract data
$crawler->filter('h2 > a')->each(function ($node) {
print $node->text()."\n";
});
Climate
Climate is a library for people who run PHP from the command line. It offers a collection of methods for talking to the terminal (both input and output), and also some beautifying functions for coloring and formatting. It can even draw and animate cool ASCII art.
$climate = new League\CLImate\CLImate;
// Output
$climate->out('This prints to the terminal.');
// Input
$input = $climate->input('How you doin?');
$response = $input->prompt();
// Formatting
$padding = $climate->padding(10);
$padding->label('Eggs')->result('$1.99');
$padding->label('Oatmeal')->result('$4.99');
// Eggs...... $1.99
// Oatmeal... $4.99
Alice
Built on top of Faker, Alice is a library that generates fake data objects for testing. To use it you first have to define the structure of your objects and what data you want in them. Then with a simple function call Alice will transform this template into an actual object with random values.
// Template in person.yml file
Person:
person{1..10}:
firstName: '<firstName()>'
lastName: '<lastName()>'
birthDate: '<date()>'
email: '<email()>'
// Load dummy data into an object
$person = \Nelmio\Alice\Fixtures::load('/person.yml', $objectManager);
Ratchet
The Ratchet library adds support for the WebSockets interface in apps with a PHP backend. WebSockets enable two-way communication between the server and client side in real time. For this to work in PHP, Ratchet has to start a separate PHP process that stays always running and asynchronously sends and receives messages.
class MyChat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from != $client) {
$client->send($msg);
}
}
}
}
// Run the server application through the WebSocket protocol on port 8080
$app = new Ratchet\App('localhost', 8080);
$app->route('/chat', new MyChat);
$app->run();
PHPMailer
No PHP library collection is complete without PHPMailer. This project is backed by a huge community and is implemented in popular systems such as WordPress and Drupal, making it the safest choice for sending emails in PHP. It has SMTP support, can do HTML-based emails, and much more.
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom('[email protected]', 'Mailer');
$mail->addAddress('[email protected]');
$mail->addAttachment('/var/tmp/file.tar.gz');
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Hoa
Hoa isn’t actually a PHP library – it’s an entire set of PHP libraries, containing all kinds of useful web development utilities. Although not all are fully documented, there are 50+ libraries right now, with new ones constantly being added. It’s completely modular so you can select only the libraries you need without any clutter.
// Hoa Mail
$message = new Hoa\Mail\Message();
$message['From'] = 'Gordon Freeman <[email protected]>';
$message['To'] = 'Alyx Vance <[email protected]>';
$message['Subject'] = 'Hoa is awesome!';
$message->addContent(
new Hoa\Mail\Content\Text('Check this out: http://hoa-project.net/!')
);
$message->send();
// Hoa Session
$user = new Hoa\Session\Session('user');
if ($user->isEmpty()) {
echo 'first time', "\n";
$user['foo'] = time();
} else {
echo 'other times', "\n";
var_dump($user['foo']);
}
CssToInlineStyles
Anyone who has tried creating HTML emails knows what a pain it is to inline all of the CSS rules. This small PHP Class does the whole job for you, saving you lots of time and nerves. Just write your styles in a regular .css file and the PHP library will use the selectors to assign them at the proper tags.
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
// create instance
$cssToInlineStyles = new CssToInlineStyles();
$html = file_get_contents(__DIR__ . '/examples/sumo/index.htm');
$css = file_get_contents(__DIR__ . '/examples/sumo/style.css');
// output
echo $cssToInlineStyles->convert(
$html,
$css
);
Stringy
Library for doing all kinds of string manipulations. It offers a ton of different methods for modifying text (reverse()
,htmlEncode()
, toAscii()
etc.) or gather information about a string (isAlphanumeric()
, getEncoding()
, among others). A cool thing about Stringy is that it also works with special symbols like Greek or Nordic letters;
s('Camel-Case')->camelize(); // 'camelCase'
s(' Ο συγγραφέας ')->collapseWhitespace(); // 'Ο συγγραφέας'
s('foo & bar')->containsAll(['foo', 'bar']); // true
s('str contains foo')->containsAny(['foo', 'bar']); // true
s('fòôbàř')->endsWith('bàř', true); // true
s('fòôbàř')->getEncoding(); // 'UTF-8'
s('&')->htmlDecode(); // '&'
Robo
Robo is a Gulp-like task runner, only for PHP. With it you can set up automations that improve your workflow and the time it takes to build a project after making changes. Robo can run tests, compile code from preprocessors, handle version control updates, and many other useful tasks.
// Doing a Git Commit with Robo
public function pharPublish()
{
$this->pharBuild()->run();
$this->_rename('robo.phar', 'robo-release.phar');
return $this->collectionBuilder()
->taskGitStack()
->checkout('gh-pages')
->taskGitStack()
->add('robo.phar')
->commit('robo.phar published')
->push('origin', 'gh-pages')
->checkout('master')
->run();
}
PHP Humanizer
This library takes variables and transforms them into a more human-readable format using a set of methods. For example it can turn Roman numerals into numbers, truncate long strings, and calculate bytes to kB/MB/GB. Support for over 15 languages (the spoken kind, not programming ones).
use Coduo\PHPHumanizer\NumberHumanizer;
echo StringHumanizer::humanize('field_name'); // "Field Name"
echo NumberHumanizer::ordinalize(1); // "1st"
echo NumberHumanizer::ordinalize(23); // "23rd"
echo NumberHumanizer::toRoman(5); // "V"
echo NumberHumanizer::fromRoman("MMMCMXCIX"); // 3999
echo NumberHumanizer::binarySuffix(1024); // "1 kB"
echo NumberHumanizer::binarySuffix(1073741824 * 2); // "2 GB"
ColorExtractor
The last item on our list is this small library for extracting colors from images. It iterates all of the pixels in a given picture and returns a palette of the colors on it sorted by total area. Developers can then use this palette to get the most dominant colors and adapt the design according to them.
require 'vendor/autoload.php';
use League\ColorExtractor\Color;
use League\ColorExtractor\Palette;
$palette = Palette::fromFilename('./some/image.png');
$topFive = $palette->getMostUsedColors(5);
$colorCount = count($palette);
$blackCount = $palette->getColorCount(Color::fromHexToInt('#000000'));
Source: tutorialZine