PHP developers should be aware of the 24 PHP class library

Source: Internet
Author: User
Tags autoload apc php framework wkhtmltopdf
24 libraries that PHP developers should know

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.

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

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 lightning-Fast 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:

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

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

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 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– The 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:

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.

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 ')), and//when the resource is output, the code is merged with 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. Picture processing of imageworkshop– layer

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:

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 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:

Require_once '/path/to/snappy/src/autoload.php '; Use knp\snappy\pdf; Initialize the library by wkhtmltopdf binary path $snappy = new Pdf ('/usr/local/bin/wkhtmltopdf '); Display the Pdfheader (' content-type:application/pdf ') in the browser by setting the Content-type header to PDF, and the header (' Content-disposition: Attachment Filename= "File.pdf"); echo $snappy->getoutput (' ');

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:

$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 (        ' ', ' = ', ' 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 of the original Underscore.js –javascript applied tool belt. The PHP version is not disappointing and supports almost all native features. Here are some examples:

__::each (Array (1, 2, 3), function ($num) {echo $num. ','; }); 1, $multiplier = 2;__::each (Array (, 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:

$headers = Array (' Accept ' = = ' Application/json '); $options = Array (' auth ' = = Array (' user ', ' pass ')); $request = Reque Sts::get (' ', $headers, $options); Var_dump ($request->status_code);//int (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.

buzz– Simple HTTP Request Library

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

$request = new Buzz\message\request (' HEAD ', '/', ' '); $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.

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.

Require_once '/path/to/goutte.phar '; Use goutte\client; $client = new Client (), $crawler = $client->request (' GET ', ''); Click link $link = $crawler->selectlink (' Plugins ')->link (); $crawler = $client->click ($link); Extract data using a class 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.

printf ("Right now was%s", Carbon::now ()->todatetimestring ());p rintf ("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 with 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:

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.123secho $bench->gettime (true); Elapsed Microtime in Floatecho $bench->gettime (False, '%d%s '); 156ms or 1secho $bench->getmemorypeak (); 152B or 90.00Kb or 15.23Mbecho $bench->getmemorypeak (true); Memories Peak in bytes memory peaks Echo $bench->getmemorypeak (False, '%.3f%s '); 152B or 90.152Kb or 15.234mb//returns memory usage at the end of the logo 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:

Use Respect\validation\validator as V; Simple verification of the------+ ()->validate (); True//chained validation $usernamevalidator = V::alnum ()->nowhitespace ()->length (1,15); $usernameValidator->validate ( ' Alganet '); True//Verify object Properties $user = new StdClass; $user->name = ' Alexandre '; $user->birthdate = ' 1987-07-01 '; Verify his properties 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:

$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– false 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:

Reference faker autoloader require_once '/path/to/faker/src/autoload.php ';//use factory creation to create a faker\generator instance $faker = Faker\factory :: Create ();//Generate 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.

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

Use Gaufrette\filesystem;use gaufrette\adapter\ftp as Ftpadapter;use gaufrette\adapter\local as LocalAdapter; Local file: $adapter = new Localadapter ('/var/media '); Optionally use an FTP adapter//$ftp = new Ftpadapter ($path, $host, $username, $password, $port); Initialize 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:

Use Omnipay\creditcard;use omnipay\gatewayfactory; $gateway = gatewayfactory::create (' Stripe '); $gateway Setapikey (' abc123 '); $formData = [' number ' = ' 4111111111111111 ', ' expirymonth ' = 6, ' expiryyear ' = 2016];$ Response = $gateway->purchase ([' Amount ' = +, ' card ' + $formData]), if ($response->issuccessful ()) {//payment Success: Update Database    Print_r ($response),} elseif ($response->isredirect ()) {//Jump to offsite payment gateway    $response->redirect ();} else {//payment failure: Show information to Customer    exit ($response->getmessage ());}

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

upload– processing file uploads

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

$storage = new \upload\storage\filesystem ('/path/to/directory '); $file = new \upload\file (' foo ', $storage);//verify File Upload $ File->addvalidations (//Ensure that the file type is "Image/png"    new \upload\validation\mimetype (' image/png '),//Ensure that the file does not exceed 5M (use "B", "K", "M" or "G")    New \upload\validation\size (' 5M '));//attempt to upload 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.

Require_once '/path/to/ '; $config = Htmlpurifier_config::createdefault (); $purifier = new Htmlpurifier ($config); $clean _html = $purifier->purify ($dirty _html);

colorjizz-php– Color Control Library

Colorjizz is a simple library that allows you to convert different color formats and do 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 already supports and can manipulate all the major color formats.

PHP geo-geo-Location Locator Library

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

Use Location\coordinate;use location\distance\vincenty; $coordinate 1 = new Coordinate (19.820664,-155.468066); Mauna Kea Summit Maui Peak $coordinate2 = new Coordinate (20.709722,-156.253333); Haleakala summit$calculator = new Vincenty (), $distance = $calculator->getdistance ($coordinate 1, $coordinate 2); Returns 128130.850 (meters;≈128 kilometers)

shellwrap– Graceful Command-line wrapper

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

Require ' shellwrap.php '; use \mrrio\shellwrap as sh; Lists all files under the current file echo Sh::ls (); Check out a git branch sh::git (' Checkout ', ' master '); You can also use the pipe to put a command output user another command//below via curl to track the location, and then filter the ' HTML ' pipeline via grep to download the website echo sh::grep (' HTML ', Sh::curl (' http:/ / ', Array (    ' location ' = + true)); Create a new file Sh::touch (' file.html '); Remove file Sh::rm (' file.html '); Remove the file again (this time it failed, and then throw 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.

  • 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: 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.