As a PHP developer, it is an exciting moment. Many useful libraries are distributed every day and can be easily found and used on Github. Below are the 24 coolest libraries I have ever met. Your favorite library is not in this list? Share it in the comments! 1. Dispatch & ndash; the micro-framework Dispatch is a small PHP framework. It does not give you the complete MVC
As a PHP developer, it is an exciting moment. Many useful libraries are distributed every day and can be easily found and used on Github. Below are the 24 coolest libraries I have ever met. Your favorite library is not in this list? Share it in the comments!
1. Dispatch-microframework
Dispatch is a small PHP framework. It does not give you complete MVC settings, but you can define URL rules and methods to better organize applications. This is perfect for APIs, simple sites, or prototypes.
// Include the Library '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 sitedispatch ();
You can match a specific type of HTTP request and path, render the view, or do more. If you merge Dispatch and other frameworks, you can have a very powerful and lightweight program!
2. Klein-PHP fast lightning-like routing
Klein is another lightweight routing library for PHP5.3 +. Although it has some lengthy syntax than Dispatch, it is quite fast. Here is an example:
respond('/[:name]', function ($request) { echo 'Hello ' . $request->name;});
You can also customize the HTTP method and use the regular expression as the path.
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 may also want to process the request 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 large applications, you have to follow the rules because your code may become unmaintainable soon. So you 'd better match a completely mature framework like Laravel or CodeIgniter.
3. Ham-routing database with cache
Ham is also a lightweight routing framework, but it uses the cache to get a faster speed. It caches any I/O-related items into XCache/APC. The following is an example:
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 XCache and APC, which may mean that it may not be used on hosts provided by most host providers. But if you have a host to install them, or you can control your web server, you should try this fastest framework.
4. Assetic-resource management
Assetic is a PHP resource management framework used to merge and reduce CSS/JS resources. The following is an example.
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 will be merged echo $ js-> dump ();
It is a good idea to merge resources in this way because it can accelerate the site. Not only does the total download volume decrease, but it also eliminates a large number of unnecessary HTTP requests (this is the two most influential aspects of page loading time)
5. ImageWorkshop-image processing with layers
ImageWorkshop is an open source library that allows you to manipulate pictures with layers. With this feature, you can redefine the size, crop, create thumbnails, add watermarks, or do more. The following is an example:
// Initialize the norway layer from the norway.jpg Image $ norwayLayer = ImageWorkshop: initFromPath ('/path/to/images/norway.jpg'); // initialize the watermark layer (watermark layer) from the watermark.png image) $ watermarkLayer = ImageWorkshop: initFromPath ('/path/to/images/watermark.png'); $ image = $ norwayLayer-> getResult (); // This is the generated image! Header ('content-type: image/jpeg '); imagejpeg ($ image, null, 95); // We choose to show a JPG with a quality of 95% exit;
ImageWorkshop is developed to simplify some of the most common cases for processing images in PHP. if you need something more powerful, you should check the Imagine library!
6. Snappy-snapshot/PDF Library
Snappy is a PHP5 database that can generate snapshots, URLs, HTML, and PDF files. Does it depend on wkhtmltopdf? Binary (available in Linux, Windows, and OSX ). You can use them like this:
Require_once '/path/to/snappy/src/autoload. php '; use Knp \ Snappy \ Pdf; // initialize the library through the wkhtmltopdf binary path $ snappy = new Pdf ('/usr/local/bin/wkhtmltopdf '); // set the Content-type header to pdf to display the response header ('content-Type: application/pdf '); header ('content-Disposition: attachment; filename = "filepath" '); echo $ snappy-> getOutput ('http: // www.github.com ');
Remember, your host provider may not be allowed to call external binaries.
7. Idiorm-lightweight ORM library
Idiorm is one of my favorite products used in this tutorial. It is a lightweight ORM library and a PHP5 query constructor built on PDO. With it, you can forget how to write boring SQL:
$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 database named Paris, which is an Idiorm-based Active Record implementation.
8. Underscore-PHP tool belt
Underscore is an interface of original Underscore. js-a tool belt for Javascript applications. The PHP version is not disappointing and supports almost all native features. The following are some examples:
__::each(array(1, 2, 3), function($num) { echo $num . ','; }); // 1,2,3,$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 the chain syntax, which makes it more powerful.
9. Requests-simple HTTP request
Requests is a library that simplifies HTTP Requests. If you are like me, you almost never remember the various parameters passed to Curl, then it is prepared for you:
$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) "[…]"
With this library, you can send HEAD, GET, POST, PUT, DELTE, and patch http requests. you can add files and parameters through arrays and access all corresponding data.
10. Buzz-simple HTTP request Library
Buzz is another library that completes HTTP requests. The following is an example:
$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.
11. Goutte-Web crawling Library
Goutte is a library that captures websites and extracts data. It provides an elegant API, which makes it easy to select a specific element from a remote page.
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 ('ins ins')-> link (); $ crawler = $ client-> click ($ link ); // Extract data using a CSS-like syntax $ t = $ crawler-> filter ('# data')-> text (); echo "Here is the text: $ t ";
12. Carbon-DateTime Library
Carbon is a simple extension of the DateTime API.
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 (); $ nextsummerolympus mpics = Carbon: createFromDate (2012)-> addYears (4); $ officialDate = Carbon: now ()-> toRFC2822String (); $ howOldAmI = Carbon :: createFromDate (1975, 5, 21)-> age; $ noonTodayLondonTime = Carb On: createFromTime (12, 0, 0, 'Europe/London '); $ endOfWorld = Carbon: createFromDate (2012, 12, 21, 'gmt '); // always compare if (Carbon: now ()-> gte ($ endOfWorld) {die ();} if (Carbon: now () -> isWeekend () {echo 'party! ';} Echo Carbon: now ()-> subMinutes (2)-> diffForHumans (); // '2 minutes ago'
13. Ubench-mini benchmark database
Ubench is a micro-library used to evaluate PHP code. it can monitor the execution time and memory usage. The following is an example:
Use Ubench \ Ubench; $ users = new Ubench; $ users-> start (); // execute some code $ users-> end (); // Obtain the execution consumption time and memory echo $ response-> getTime (); // 156 ms or 1.123 secho $ response-> getTime (true ); // elapsed microtime in floatecho $ response-> getTime (false, '% d % S'); // 156 ms or 1 secho $ response-> getMemoryPeak (); // 152B or 90.00Kb or 15.23 Mbecho $ response-> getMemoryPeak (true); // memory peak in bytes peak memory echo $ response-> getMemoryPeak (false, '%. 3f % s '); // 152B or 90.152Kb or 15.234 Mb // the memory usage is returned at the end Mark echo $ response-> getMemoryUsage (); // 152B or 90.00Kb or 15.23 Mb
(Only) it is a good idea to run these verifications during development.
14. Validation-input verification engine
Validation? It is claimed to be the most powerful verification engine in the PHP library. But is it true? See the following:
Use Respect \ Validation \ Validator as v; // simple verification $ number = 123; v: numeric ()-> validate ($ number ); // true // chain verification $ usernameValidator = v: alnum ()-> noWhitespace ()-> length (); $ usernameValidator-> validate ('alganet '); // true // verify object attributes $ user = new stdClass; $ user-> name = 'alexre'; $ user-> birthdate = '2017-07-01 '; // verify its attributes in a simple chain $ userValidator = v: attribute ('name', v: string ()-> length )) -> attribute ('birthdate', v: date ()-> minimumAge (18); $ userValidator-> validate ($ user); // true
You can use this library to verify the data submitted by your form or other users. In addition, it has a lot of built-in validation, throwing exceptions and custom error messages.
15. Filterus-filter Library
Filterus is another filtering library, but it can not only verify, but also filter the output matching the preset mode. The following is an example:
$f = Filter::factory('string,max:5');$str = 'This is a test string'; $f->validate($str); // false$f->filter($str); // 'This '
Filterus has many built-in modes that support chained usage. you can even use independent verification rules to verify array elements.
16. Faker-false data generator
Faker? Is a PHP library that generates fake data for you. It can be used when you need to fill in a Test database or generate test data for your web application. It is also very easy to use:
// Reference the Faker automatic loader require_once '/path/to/Faker/src/autoload. php '; // create a Faker \ Generator instance using the Factory $ faker = Faker \ Factory: create (); // generate false data 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 long as you continue to access the object property, it will continue to return randomly generated data.
17. Mustache. php-elegant Template Library
Mustache is a popular template language that has been actually implemented in various programming languages. You can use it to reuse templates on the client or service segment. As you guessed, Mustache. php? Is implemented using PHP.
$m = new Mustache_Engine;echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!"
I suggest you check the official website Mustache docs? See more advanced examples.
18. Gaufrette-file system abstraction layer
Gaufrette is a PHP5 library that provides an abstraction layer for a file system. It allows you to manipulate local files, FTP servers, Amazon S3, or more in the same way. It allows you to develop programs without understanding how you will access your files in the future.
Use Gaufrette \ Filesystem; use Gaufrette \ Adapter \ Ftp as FtpAdapter; use Gaufrette \ Adapter \ Local as LocalAdapter; // Local File: $ adapter = new LocalAdapter ('/var/media'); // An FTP adapter // $ ftp = new FtpAdapter ($ path, $ host, $ username, $ password, $ port); // initialize 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 more adapters will be added later.
19. Omnipay-Payment Processing database
Omnipay is a PHP payment processing library. It has a clear and consistent API and supports dozens of gateways. To use this library, you only need to learn an API and process various payment processors. The following is an example:
Use Omnipay \ CreditCard; use Omnipay \ GatewayFactory; $ gateway = GatewayFactory: create ('string'); $ gateway-> setApiKey ('abc123 '); $ formData = ['Number' => '000000', 'expirymonth' => 6, 'expiryyear '=> 4111111111111111]; $ response = $ gateway-> purchase (['amount '=> 1000, 'card' => $ formData]); if ($ response-> isSuccessful ()) {// payment successful: update the database print_r ($ response);} elseif ($ response-> isRedirect ()) {// jump to the remote payment gateway $ response-> redirect ();} else {// payment failed: display the information to the customer exit ($ response-> getMessage ());}
With the same API, you can easily support multiple payment processors or switch between them as needed.
20. Upload-process file Upload
Upload is a library that simplifies file Upload and verification. When a form is uploaded, the library verifies the file type and size.
$ Storage = new \ Upload \ Storage \ FileSystem ('/path/to/directory'); $ file = new \ Upload \ File ('foo', $ storage ); // verify the file Upload $ file-> addValidations (array (// make sure the file type is "image/png" new \ Upload \ Validation \ Mimetype ('image/png '), // make sure the file size does not exceed 5 MB (use "B", "K", "M" or "G ") new \ Upload \ Validation \ Size ('5'); // try to upload a file {// success $ file-> Upload ();} catch (\ Exception $ e) {// failed! $ Errors = $ file-> getErrors ();}
It will reduce a lot of tedious code.
21. HTMLPurifier-html xss protection
HTMLPurifier is an HTML filter library that protects your code from XSS attacks through powerful whitelist and clustering analysis. It also ensures that the output tag complies with the standard .? (Source code is on github)
require_once '/path/to/HTMLPurifier.auto.php';$config = HTMLPurifier_Config::createDefault();$purifier = new HTMLPurifier($config);$clean_html = $purifier->purify($dirty_html);
If your website allows users to submit HTML code and the code is displayed without modification, it is time to use this library.
22. ColorJizz-PHP-color control Library
ColorJizz is a simple library that allows you to convert different color formats and perform simple color operations.
use MischiefCollective\ColorJizz\Formats\Hex;$red_hex = new Hex(0xFF0000);$red_cmyk = $hex->toCMYK();echo $red_cmyk; // 0,1,1,0echo Hex::fromString('red')->hue(-20)->greyscale(); // 555555
It supports and can control all mainstream color formats.
23. PHP Geo-location Library
Phpgeo is a simple library used to calculate the precise distance between geographical coordinates. For example:
Use Location \ Coordinate; use Location \ Distance \ Vincenty; $ coordinate1 = new Coordinate (19.820664,-155.468066); // Mauna Kea Summit manakai peak $ coordinate2 = new Coordinate (20.709722, -156.253333); // Haleakala Summit $ calculator = new Vincenty (); $ distance = $ calculator-> getDistance ($ coordinate1, $ coordinate2); // returns 128130.850 (meters; ≈ 128 kilometers)
It will work well in apps that use location data. You can try to translate HTML5 Location API, Yahoo API (or both, we did this in weather web app tutorial) to get coordinates.
24. ShellWrap-elegant command line wrappers
With? ShellWrap? Library, you can use a powerful Linux/Unix command line tool in PHP code.
Require 'shellwrap. php '; use \ MrRio \ ShellWrap as sh; // list all the files in the current file echo sh: ls (); // Check out a git branch sh :: git ('checkout', 'Master'); // You can also use the pipeline to output a command to another user. // The location is tracked through curl below, then, use the grep filter 'HTML 'pipeline to download the example.com website echo sh: grep ('html', sh: curl ('http: // example.com ', array ('location' => true); // create a file sh: touch('file.html '); // remove the file sh: rm('file.html '); // remove the file again (this time failed, and an Exception is thrown because the file does not exist) try {sh: rm('file.html ');} catch (Exception $ e) {echo 'caught failing sh: rm () call ';}
When an exception occurs in the command line, this database throws an exception, so you can promptly respond to it. It can also allow you to use the output of one command as the input of another command through the pipeline to achieve more flexibility.