PHP Libraries For Summer 2016


 
 

Here are our picks for the 12 most useful and interesting open-source PHP libraries that you should check out this summer!

 

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

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();

 

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); }

 

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'));

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();

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('&amp;')->htmlDecode(); // '&'

 

 
 

tags: php php libraries monolog whoops fastCache codinng developers


Comments area, use one of your social accounts to log-in and post a comment.



Responses to the post

We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .