ruk·si

🐘 PHP
Libraries

Updated at 2014-05-19 11:17

This note contains interesting PHP libraries and frameworks that people should know about.

Klein

Lightning fast routing. Use for small websites and small web applications.

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

respond('GET', '/posts', $callback);
respond('POST', '/posts/create', $callback);
respond('PUT', '/posts/[i:id]', $callback);
respond('DELETE', '/posts/[i:id]', $callback);

// To match multiple request methods:
respond(array('POST','GET'), $route, $callback);

// Or you might want to handle the requests in the same place
respond('/posts/[create|edit:action]?/[i:id]?', function ($request, $response) {
    switch ($request->action) {
        // do something
    }
});

// Send a file
$klein->respond('/report/latest', function ($request, $response, $service) {
    $service->file('/tmp/cached_report.zip');
});

WordPress

Good out-of-the-box content management system. Use for small and medium websites.

Try these plugins:

  • WooCommerce + Plugins
  • Advanced Custom Fields + Plugins
  • W3 Total Cache
  • WP Smush.it
  • Akismet
  • WordPress SEO by Yoast
  • Gravity Forms

Drupal

More flexible, but also more complex, content management system. Use for medium to large websites.

Laravel

PHP framework for web applications. Use when a website has a lot of interaction.

Assetic

Asset management that minimizes your CSS and JS, compiles your LESS and SASS, optimizes your images.

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

// the code is merged when the asset is dumped
echo $js->dump();

ImageWorkshop

Image manipulation.

// We initialize the norway layer from the picture norway.jpg.
$norwayLayer = ImageWorkshop::initFromPath('/path/to/images/norway.jpg');

// We initialize the watermark layer from the picture watermark.png.
$watermarkLayer = ImageWorkshop::initFromPath('/path/to/images/watermark.png');

// This is the generated image.
$image = $norwayLayer->getResult();

// We choose to show a JPG with a quality of 95%.
header('Content-type: image/jpeg');
imagejpeg($image, null, 95);
exit;

Snappy

Take snapshots of HTML pages.

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

Requests

Easy way to issue HTTP requests. Abstraction for curl and fsockopen.

$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) '...'

Carbon

A simple API extension for the DateTime.

printf('Right now is %s', Carbon::now()->toDateTimeString());
printf('Right now in Vancouver is %s', Carbon::now('America/Vancouver'));

$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();
$nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);

$officialDate = Carbon::now()->toRFC2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$endOfWorld = Carbon::createFromDate(2012, 12, 21, 'GMT');

if ( Carbon::now()->isWeekend() ) {
    echo 'Party!';
}

// Comparisons are always done in UTC
$first = Carbon::create(2012, 1, 1, 0, 0, 0);
$second = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Vancouver');
var_dump($first->eq($second));                     // bool(false)
var_dump($first->ne($second));                     // bool(true)
var_dump($first->gt($second));                     // bool(false)
var_dump($first->gte($second));                    // bool(false)
var_dump($first->lt($second));                     // bool(true)
var_dump($first->lte($second));                    // bool(true)

echo Carbon::now()->subMinutes(2)->diffForHumans();
// => '2 minutes ago'

$now = Carbon::now();
echo $now;
// => 2012-10-14 20:40:20

$yesterday = Carbon::yesterday();
echo $yesterday;
// => 2012-10-13 00:00:00

Validation

Validation library for PHP.

use Respect\Validation\Validator as v;

// Simple Validation
$number = 123;
v::numeric()->validate($number);
// => true

// Chained Validation
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate('alganet');
// => true

// Validating Object Attributes
$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);
// => true

Mustache

String templating for PHP. Helps you to reduce logic in your templates.

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

Omnipay

Payment library

use Omnipay\CreditCard;
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()) {
    // payment was successful: update database
    print_r($response);
} elseif ($response->isRedirect()) {
    // redirect to offsite payment gateway
    $response->redirect();
} else {
    // payment failed: display message to customer
    exit($response->getMessage());
}

Upload

Uploading files.

$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);

// Validate file upload
$file->addValidations(array(
    // Ensure file is of type 'image/png'
    new \Upload\Validation\Mimetype('image/png'),

    // Ensure file is no larger than 5M (use 'B', 'K', 'M', or 'G')
    new \Upload\Validation\Size('5M')
));

// Try to upload file
try {
    // Success!
    $file->upload();
} catch (\Exception $e) {
    // Fail!
    $errors = $file->getErrors();
}

HTML Purifier

XSS protection.

require_once '/path/to/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);

ColorJizz

Manipulates colors.

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

PHPGeo

Geo location library.

use Location\Coordinate;
use Location\Distance\Vincenty;

// Mauna Kea Summit
$coordinate1 = new Coordinate(19.820664, -155.468066);
// Haleakala Summit
$coordinate2 = new Coordinate(20.709722, -156.253333);

$calculator = new Vincenty();
$distance = $calculator->getDistance($coordinate1, $coordinate2);
// returns 128130.850 (meters; ≈128 kilometers)