PHP Libraries For Summer 2016

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

 

 
by Janeth Kent Date: 11-08-2016 php php libraries monolog whoops fastCache codinng developers hits : 7746  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

Examine the 10 key PHP functions I use frequently

PHP never ceases to surprise me with its built-in capabilities. These are a few of the functions I find most fascinating.   1. Levenshtein This function uses the Levenshtein algorithm to calculate the…

How to Track Flight Status in real-time using the Flight Tracker API

The Flight Tracker API provides developers with the ability to access real-time flight status, which is extremely useful for integrating historical tracking or live queries of air traffic into your…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

PHP - The Singleton Pattern

The Singleton Pattern is one of the GoF (Gang of Four) Patterns. This particular pattern provides a method for limiting the number of instances of an object to just one.…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

The State of PHP 8: new features and changes

PHP 8.0 has been released last November 26: let's discover together the main innovations that the new version introduces in this language. PHP is one of the most popular programming languages…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The most popular Array Sorting Algorithms In PHP

There are many ways to sort an array in PHP, the easiest being to use the sort() function built into PHP. This sort function is quick but has it's limitations,…

MySQL 8.0 is now fully supported in PHP 7.4

MySQL and PHP is a love story that started long time ago. However the love story with MySQL 8.0 was a bit slower to start… but don’t worry it rules…

A roadmap to becoming a web developer in 2019

There are plenty of tutorials online, which won't cost you a cent. If you are sufficiently self-driven and interested, you have no difficulty training yourself. The point to learn coding…

10 PHP code snippets to work with dates

Here we have some set of Useful PHP Snippets, which are useful for PHP Developers. In this tutorial we'll show you the 10 PHP date snippets you can use on…

8 Free PHP Books to Read in Summer 2018

In this article, we've listed 8 free PHP books that can help you to learn new approaches to solving problems and keep your skill up to date.   Practical PHP Testing This book…

Clicky