PHP developers should be aware of the 24 cool PHP libraries (micro-framework)

Source: Internet
Author: User
Tags autoload apc wkhtmltopdf
PHP developers should be aware of the 24 cool PHP libraries (micro-framework)

As a PHP developer, now is an exciting time. Many useful libraries are distributed every day, and these libraries are easy to discover and use on GitHub. Here are some of the coolest 24 libraries I've ever met. Is your favorite library not in this list? Let's share it in the comments!

1. Dispatch? Micro Frame

Dispatch is a small PHP framework. It doesn't give you full MVC settings, but you can define URL rules and methods to better organize your application. This is perfect for APIs, simple sites, or prototypes.

[PHP] view plaincopy

Include Library

Include ' dispatch.php ';

Define your route

Get ('/greet ', function () {

Render View

Render (' Greet-form ');

});

Post processing

Post ('/greet ', function () {

$name = from ($_post, ' name ');

Render a view while passing some locals

Render (' Greet-show ', Array (' name ' = = $name));

});

Serve your site

Dispatch ();


You can match specific types of HTTP requests and paths, render views, or do more things. If you merge dispatch and other frameworks, you can have a fairly powerful and lightweight program!

2. Klein? PHP Fast lightning-like routing

Klein is another lightweight routing library for the php5.3+ version. Although it has some verbose syntax than dispatch, it's pretty fast. Here's an example:

[PHP] view plaincopy

Respond ('/[:name] ', function ($request) {

Echo ' Hello '. $request->name;

});


You can also customize to specify HTTP methods and use regular expressions as paths.

[PHP] view plaincopy

Respond (' GET ', '/posts ', $callback);

Respond (' POST ', '/posts/create ', $callback);

Respond (' PUT ', '/posts/[i:id] ', $callback);

Respond (' DELETE ', '/posts/[i:id] ', $callback);

Match multiple Request methods:

Respond (Array (' POST ', ' GET '), $route, $callback);

You might also want to handle requests in the same place.

Respond ('/posts/[create|edit:action]/[i:id] ', function ($request, $response) {

Switch ($request->action) {

Do something

}

});


This is great for small projects, but when you use a library like this for a large application, you have to follow the rules, because your code can quickly become non-maintainable. So you'd better go with a fully fledged framework like laravel or CodeIgniter.

3. Ham? Routing Library with cache

Ham is also a lightweight routing framework, but it takes advantage of caching to get even faster. It caches any I/O-related stuff into the XCACHE/APC. Here is an example:

[PHP] view plaincopy

Require '. /ham/ham.php ';

$app = new Ham (' example ');

$app->config_from_file (' settings.php ');

$app->route ('/pork ', function ($app) {

Return "Delicious pork.";

});

$hello = function ($app, $name = ' world ') {

return $app->render (' hello.html ', Array (

' Name ' = $name

));

};

$app->route ('/hello/ ', $hello);

$app->route ('/', $hello);

$app->run ();


This library requires you to install at least one of the XCache and APC, which may mean that it may not be available on most hosts provided by the host provider. But if you have a host that installs them, or you can manipulate your Web server, you should try this fastest framework.

4. assetic? Resource Management

Assetic is a PHP resource management framework for merging and reducing CSS/JS resources. Here is an example.

[PHP] view plaincopy

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

));

When the resource is output, the code is merged

echo $js->dump ();


Merging resources in this way is a good idea because it can speed up the site. Not only does the total download decrease, but it also eliminates a lot of unnecessary HTTP requests (two things that most affect page load times)

5. Imageworkshop? Picture processing with layers

Imageworkshop is an open source library that lets you manipulate images with layers. With it you can redefine dimensions, crop, make thumbnails, draw water or do more. Here is an example:

[PHP] view plaincopy

Initialize Norway layer from Norway.jpg pictures

$norwayLayer = Imageworkshop::initfrompath ('/path/to/images/norway.jpg ');

Initialize the watermark layer (watermark layer) from the Watermark.png picture

$watermarkLayer = Imageworkshop::initfrompath ('/path/to/images/watermark.png ');

$image = $norwayLayer->getresult (); This is the generated picture!

Header (' Content-type:image/jpeg ');

imagejpeg ($image, NULL, 95); We choose to show a JPG with a quality of 95%

Exit


Imageworkshop was developed to simplify some of the most common cases of processing pictures in PHP, and if you need something more powerful, you should look at Imagine library!

6. Snappy? Snapshot/pdf Library

Snappy is a PHP5 library that can generate snapshots, URLs, HTML, and PDFs. It relies on wkhtmltopdf binary (available on both linux,windows and OSX). You can use them like this:

[PHP] view plaincopy

Require_once '/path/to/snappy/src/autoload.php ';

Use knp\snappy\pdf;

Initializing a library by wkhtmltopdf binary path

$snappy = new Pdf ('/usr/local/bin/wkhtmltopdf ');

Display PDFs in a browser by setting the Content-type header to PDF

Header (' content-type:application/pdf ');

Header (' content-disposition:attachment; filename= ' file.pdf ');

echo $snappy->getoutput (' http://www.github.com ');


Remember that your hosting provider may not allow calls to external binaries.

7. Idiorm? Lightweight ORM Library

Idiorm is one of the most popular tutorials you've ever used in this website. It is a lightweight ORM library, a PHP5 query builder built on PDO. With it, you can forget how to write tedious sql:

[PHP] view plaincopy

$user = orm::for_table (' user ')

->where_equal (' username ', ' j4mie ')

->find_one ();

$user->first_name = ' Jamie ';

$user->save ();

$tweets = orm::for_table (' tweet ')

->select (' tweet.* ')

->join (' user ', array (

' User.ID ', ' = ', ' tweet.user_id '

))

->where_equal (' User.username ', ' J4mie ')

->find_many ();

foreach ($tweets as $tweet) {

Echo $tweet->text;

}


Idiorm has a sister library called Paris,paris is a idiorm-based active record implementation.

8. Underscore? PHP's Tool belt

Underscore is an interface to the original underscore.js? Tool belt for JavaScript applications. The PHP version is not disappointing and supports almost all native features. Here are some examples:

[PHP] view plaincopy

__::each (Array (1, 2, 3), function ($num) {echo $num. ','; }); ,

$multiplier = 2;

__::each (Array (1, 2, 3), function ($num, $index) use ($multiplier) {

Echo $index. '=' . ($num * $multiplier). ',';

});

Prints:0=2,1=4,2=6,

__::reduce (Array (1, 2, 3), function ($memo, $num) {return $memo + $num;}, 0); 6

__::find (Array (1, 2, 3, 4), function ($num) {return $num% 2 = = 0;}); 2

__::filter (Array (1, 2, 3, 4), function ($num) {return $num% 2 = = 0;}); Array (2, 4)


This library also supports chained syntax, which makes it more powerful.

9. Requests? Simple HTTP request

Requests is a library that simplifies HTTP requests. If you are like me, almost never remember the various parameters passed to curl, then it is for you:

[PHP] view plaincopy

$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 (+) "Application/json; Charset=utf-8 "

Var_dump ($request->body);

String (26891) "[...]"


With this library, you can send head, GET, POST, PUT, delte, and patch HTTP requests, you can add files and parameters through an array, and you can access all the corresponding data.

Ten. Buzz? A simple HTTP request library

Buzz is another library that completes HTTP requests. Here is an example:

[PHP] view plaincopy

$request = new Buzz\message\request (' HEAD ', '/', ' http://google.com ');

$response = new Buzz\message\response ();

$client = new Buzz\client\filegetcontents ();

$client->send ($request, $response);

Echo $request;

Echo $response;


Because it lacks documentation, you have to read the source code to learn all the parameters it supports.

A. Goutte? Web Crawl Library

Goutte is a library that crawls Web sites and extracts data. It provides an elegant API that makes it easy to select specific elements from a remote page.

[PHP] view plaincopy

Require_once '/path/to/goutte.phar ';

Use goutte\client;

$client = new Client ();

$crawler = $client->request (' GET ', ' http://www.symfony-project.org/');

Click the link

$link = $crawler->selectlink (' Plugins ')->link ();

$crawler = $client->click ($link);

Extracting data using a class of CSS syntax

$t = $crawler->filter (' #data ')->text ();

echo "Here is the text: $t";


Carbon? DateTime Library

Carbon is a simple extension of the DateTime API.

[PHP] view plaincopy

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

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

$howOldAmI = Carbon::createfromdate (1975, 5, +)->age;

$noonTodayLondonTime = carbon::createfromtime (0, 0, ' Europe/london ');

$endOfWorld = Carbon::createfromdate (+, +, ' GMT ');

Always compare in UTC

if (Carbon::now ()->gte ($endOfWorld)) {

Die ();

}

if (Carbon::now ()->isweekend ()) {

Echo ' party! ';

}

Echo Carbon::now ()->subminutes (2)->diffforhumans (); ' 2 minutes ago '


Ubench? Micro Benchmark Library

Ubench is a miniature library for evaluating PHP code that can monitor (code) execution time and memory usage. Here's an example:

[PHP] view plaincopy

Use Ubench\ubench;

$bench = new Ubench;

$bench->start ();

Execute some code

$bench->end ();

Get execution consumption time and memory

echo $bench->gettime (); 156ms or 1.123s

Echo $bench->gettime (TRUE); Elapsed Microtime in float

Echo $bench->gettime (False, '%d%s '); 156ms or 1s

echo $bench->getmemorypeak (); 152B or 90.00Kb or 15.23Mb

Echo $bench->getmemorypeak (TRUE); Memory Peak in bytes

Echo $bench->getmemorypeak (False, '%.3f%s '); 152B or 90.152Kb or 15.234Mb

Return memory usage at end of identity

echo $bench->getmemoryusage (); 152B or 90.00Kb or 15.23Mb


It is a good idea to run these checks at development time.

Validation? Input validation engine

Validation claims to be the most powerful authentication engine in the PHP library. But can it be a veritable? See below:

[PHP] view plaincopy

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 Properties

$user = new StdClass;

$user->name = ' Alexandre ';

$user->birthdate = ' 1987-07-01 ';

Verify his attributes in a simple chain

$userValidator = V::attribute (' name ', v::string ()->length (1,32))

->attribute (' Birthdate ', V::d ate ()->minimumage (18));

$userValidator->validate ($user); True


You can verify your form or other user-submitted data through this library. In addition, it contains a lot of checks, throws exceptions and custom error messages.

Filterus? Filter Library

Filterus is another filter library, but it can not only verify, but also filter the output that matches the preset mode. Here is an example:

[PHP] view plaincopy

$f = filter::factory (' String,max:5 ');

$str = ' This is a test string ';

$f->validate ($STR); False

$f->filter ($STR); ' This '


Filterus has a number of built-in patterns that support chained usage and can even validate array elements with independent validation rules.

Faker? Fake Data generator

Faker is a PHP library that generates fake data for you. It can be useful when you need to populate a test database, or generate test data for your web app. It is also very easy to use:

[PHP] view plaincopy

Referencing the Faker Auto Loader

Require_once '/path/to/faker/src/autoload.php ';

Use factory creation to create a Faker\generator instance

$faker = Faker\factory::create ();

Generating false data by accessing properties

Echo $faker->name; ' Lucy cechtelar ';

Echo $faker->address;

"426 Jordy Lodge

Cartwrightshire, SC 88120-6700 "

Echo $faker->text;

Sint velit Eveniet. Rerum atque repellat voluptatem quia ...


As soon as you continue to access the object properties, it will continue to return randomly generated data.

Mustache.php? Elegant Template Gallery

Mustache is a popular template language that has actually been implemented in a variety of programming languages. With it, you can reuse templates in the client or service segment. As you can guess, mustache.php is implemented using PHP.

[PHP] view plaincopy

$m = new Mustache_engine;

echo $m->render (' Hello {{planet}} ', Array (' planet ' = ' world! ')); "Hello world!"


It is recommended to take a look at the official website mustache docs to see more advanced examples.

Gaufrette? File System Abstraction Layer

Gaufrette is a PHP5 library that provides an abstraction layer of a file system. It makes it possible to manipulate local files in the same way, FTP servers, Amazon S3, or more. It allows you to develop programs without knowing how you will access your files in the future.

[PHP] view plaincopy

Use Gaufrette\filesystem;

Use gaufrette\adapter\ftp as Ftpadapter;

Use gaufrette\adapter\local as Localadapter;

Local Files:

$adapter = new Localadapter ('/var/media ');

Optionally, use an FTP adapter

$ftp = new Ftpadapter ($path, $host, $username, $password, $port);

Initializing the file system

$filesystem = new filesystem ($adapter);

Use it

$content = $filesystem->read (' myFile ');

$content = ' Hello I am the new content ';

$filesystem->write (' MyFile ', $content);


There are also cache and memory adapters, and additional adapters will be added later.

Omnipay? Payment Processing Library

Omnipay is a PHP payment processing library. It has a clear and consistent API and supports dozens of gateways. Using this library, you just need to learn an API and handle a wide variety of payment processors. Here is an example:

[PHP] view plaincopy

Use Omnipay\creditcard;

Use Omnipay\gatewayfactory;

$gateway = gatewayfactory::create (' Stripe ');

$gateway->setapikey (' abc123 ');

$formData = [' number ' = ' 4111111111111111 ', ' expirymonth ' = ' 6 ', ' expiryyear ' and ' = 2016];

$response = $gateway->purchase ([' Amount ' = +, ' card ' + $formData]);

if ($response->issuccessful ()) {

Payment Success: Update database

Print_r ($response);

} elseif ($response->isredirect ()) {

Jump to an offsite payment gateway

$response->redirect ();

} else {

Payment failure: displaying information to customers

Exit ($response->getmessage ());

}


With the same consistent API, it is easy to support multiple payment processors, or to switch when needed.

Upload? Handling file Uploads

Upload is a library for simplifying file uploads and validations. When uploading a form, the library verifies the file type and size.

[PHP] view plaincopy

$storage = new \upload\storage\filesystem ('/path/to/directory ');

$file = new \upload\file (' foo ', $storage);

Verifying file Uploads

$file->addvalidations (Array (

Make sure the file type is "Image/png"

New \upload\validation\mimetype (' Image/png '),

Make sure the file does not exceed 5M (using "B", "K", "M" or "G")

New \upload\validation\size (' 5M ')

));

Trying to upload a file

try {

Success

$file->upload ();

} catch (\exception $e) {

Failed!

$errors = $file->geterrors ();

}


It will reduce a lot of tedious code.

Htmlpurifier? HTML XSS Protection

Htmlpurifier is an HTML filtering library that protects your code from XSS attacks with powerful whitelisting and aggregation analysis. It also ensures that the output markings conform to the standard. (Source on GitHub)

[PHP] view plaincopy

Require_once '/path/to/htmlpurifier.auto.php ';

$config = Htmlpurifier_config::createdefault ();

$purifier = new Htmlpurifier ($config);

$clean _html = $purifier->purify ($dirty _html);


If your site allows users to submit HTML code and display the code without modification, then this is the time to use the library.

Colorjizz-php? Color Control Library

Colorjizz is a simple library that allows you to convert different color formats and do simple color operations

[PHP] view plaincopy

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


It already supports and can manipulate all the major color formats.

. PHP Geo? Location Locator Library

Phpgeo is a simple library for calculating high-precision distances between geographic coordinates. For example:

[PHP] view plaincopy

Use Location\coordinate;

Use Location\distance\vincenty;

$coordinate 1 = new Coordinate (19.820664,-155.468066); Mauna Kea Summit Mau na pk

$coordinate 2 = new Coordinate (20.709722,-156.253333); Haleakala Summit

$calculator = new Vincenty ();

$distance = $calculator->getdistance ($coordinate 1, $coordinate 2); Returns 128130.850 (meters;≈128 kilometers)


It will work well in apps that use geolocation data. You can try to translate HTML5 location API, Yahoo's API (or both, we did this in weather web App tutorial) to get coordinates.

Shellwrap? Graceful command-line wrapper

With the Shellwrap library, you can use powerful Linux/unix command-line tools in your PHP code.

[PHP] view plaincopy

Require ' shellwrap.php ';

Use \mrrio\shellwrap as SH;

List all files under the current file

Echo Sh::ls ();

Check out a git branch

Sh::git (' Checkout ', ' master ');

You can also send a command to the output user by pipe another command

Following the location via curl, and then filtering the ' HTML ' pipeline via grep to download the example.com website

echo sh::grep (' HTML ', Sh::curl (' http://example.com ', Array (

' Location ' = True

)));

Create a new file

Sh::touch (' file.html ');

Remove files from

SH::RM (' file.html ');

Remove the file again (this time it fails and throws an exception because the file does not exist)

try {

SH::RM (' file.html ');

} catch (Exception $e) {

Echo ' caught failing sh::rm () call ';

}


When an exception occurs at the command line, the library throws an exception, so you can react to it in a timely manner. It also allows you to get more flexibility by piping the output of one command as input to another command.

Reference Source:
PHP developers should be aware of the 24 cool PHP libraries (micro-framework)
Http://www.lai18.com/content/319592.html

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.