Home  >  Article  >  Backend Development  >  24 Libraries PHP Developers Should Know

24 Libraries PHP Developers Should Know

WBOY
WBOYOriginal
2016-08-08 09:26:20953browse

It’s an exciting time to be a PHP developer. There are tons of useful libraries distributed every day that are easy to discover and use on Github. Below are 24 of the coolest libraries I've ever come across. Is your favorite library not on this list? Then share it in the comments!

1. Dispatch – micro-framework

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

,

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15. 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 patch(); You can match specific types of HTTP requests and paths, render views or do more. If you combine Dispatch with other frameworks, you can have a very powerful and lightweight program! 2. Klein – Lightning-fast routing for PHP

Klein is another lightweight routing library for PHP5.3+. Although it has a somewhat more verbose syntax than Dispatch, it is quite fast. Here's an example:

1

2

3
respond(

'/[:name]'

,

function

(

$request) {'Hello '67

echo

.

$request->name; });

You can also customize it to specify the HTTP method and use regular expressions as paths. 12

3

4

5
8

9

10

1112,

13

14

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 placerespond('/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 unmaintainable. So you'd better go with a fully mature framework like Laravel or CodeIgniter.

3. Ham – Routing library with cache

Ham is also a lightweight routing framework, but it uses caching to achieve even faster speeds. It does this by caching anything I/O related into XCache/APC. Here is an example:

This library requires you to have at least one of XCache and APC installed, which may mean However, it may not work on most hosting providers. But if you have a host with one of them installed, or you have control over your web server, you should try this fastest framework.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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

4. Assetic - Resource Management Assetic is a PHP resource management framework for merging and reducing CSS/JS resources. Below are examples.

1

2
3

4

5

6

7

8

9

10

11

use
AsseticAssetAssetCollection;

useAsseticAssetFileAsset;

useAsseticAssetGlobAsset;

$js=

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

Combining resources in this way is a good idea as it speeds up the site. Not only the total download volume is reduced, but also a large number of unnecessary HTTP requests are eliminated (these are the two things that most affect page load time)

5. ImageWorkshop – Image processing with layers

ImageWorkshop is a tool that allows you to control An open source library for layered images. With it you can resize, crop, create thumbnails, watermark or do more. Here is an example:

1

2

3

4

5

6

7

8

9

10

11

// 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 was developed to enable some of the most versatile image processing cases in PHP Simplified, if you need something more powerful, you should check out the Imagine library!

6. Snappy - Snapshot/PDF library

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

1

2

3

4

5

6

7

8

9

10

11

12

13

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

useKnpSnappyPdf;

//Initialize the library through wkhtmltopdf binary path

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

//Display pdf in the 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, your host provides Vendors may not allow calls to external binaries.

7. Idiorm - lightweight ORM library

Idiorm is my favorite one that I have used in the tutorials on this website before. It is a lightweight ORM library, a PHP5 query builder built on PDO. With it, you can forget how to write boring SQL:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$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 

,

) {

​​​ echo$tweet->text;}

Idiorm has a sister library called Paris, which is an Active Record implementation based on Idiorm.

8. Underscore - A tool belt for PHP

Underscore is an interface to the original Underscore.js - a tool belt for Javascript applications. The PHP version does not disappoint and supports almost all native features. Here are some examples:

1

2

3

4

5

6

7

8

9

10

11

12

13

__::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 chain syntax, which makes it More powerful.

9. Requests - Simple HTTP Requests

Requests is a library that simplifies HTTP requests. If you're like me and can almost never remember the various parameters passed to Curl, then this is for you:

1

2

3

4

5

6

7

8

9

10

11

12

$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 the help of this library, you can send HEAD, GET, POST, PUT , DELTE and PATCH HTTP requests, you can add files and parameters through arrays and have access to all corresponding data.

10. Buzz – Simple HTTP request library

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

1

2

3

4

5

6

7

8

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

$response= newBuzzMessageResponse();

$cl ient= newBuzzClientFileGetContents();

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

echo$request;

echo$response;

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

11. Goutte – Web Scraping Library

Goutte is a library for crawling websites and extracting data. It provides an elegant API that makes it easy to select specific elements from remote pages.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

useGoutteClient;

$client = newClient();

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

//Click the link

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

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

//Use a CSS-like syntax to extract data

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

echo"Here is the text: $t";

12. Carbon - DateTime library

Carbon is a simple extension of the DateTime API.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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

//Always compare with UTC

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

die();

}

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

echo'Party!';

}

echoCarbon::now()->subMinutes(2 )->diffForHumans (); // '2 minutes ago'

13. Ubench – Micro Benchmark Library

Ubench is a micro library for benchmarking PHP code, monitoring (code) execution time and memory usage. Here is an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

useUbenchUbench;

$bench= newUbench;

$bench->start();

//Execute some code

$bench->end();

//Get Execution time and memory consumption

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 memory peak

echo$bench->getMemoryPeak(false, '%.3f%s'); // 152B or 90.152Kb or 15.234Mb

//Return memory usage at the end mark

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

(only) It’s a good idea to run these checks during development.

14. Validation – Input validation engine

Validation claims to be the most powerful validation engine in the PHP library. But does it live up to its name? Watch below:

Filterus is another filtering library, but it can not only verify, but also filter the output matching the preset pattern. Here is an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

useRespectValidationValidator asv ;

//Simple verification

$number = 123;

v::numeric()->validate($number); //true

//Chain validation

$usernameValidator= v::alnum()->noWhitespace()->length(1,15);

$ usernameValidator->validate('alganet'); //true

//Verify object properties

$user= newstdClass;

$user->name = 'Alexandre';

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

//Validate his attributes in a simple chain

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

                                                             8 )); $userValidator->validate($user);

//true

You can validate your form or other user submitted data through this library. In addition, it has a lot of built-in validation, throwing exceptions and custom error messages.

15. Filterus - Filtering library

1

2

3

45);

$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, supports chain usage, and can even use independent validation rules to validate array elements.

16. Faker - Fake Data Generator

Faker is a PHP library that generates fake data for you. This comes in handy when you need to populate a test database, or generate test data for your web application. It's also very easy to use:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//Reference Faker autoloader

require_once'/path/to/Faker/src/autoload.php';

// Use factory creation to create a FakerGenerator instance

$faker= FakerFactory::create();

//Generate fake 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 long as you continue to access object properties, it will continue to return randomly generated data.

17. Mustache.php - Elegant template library

Mustache is a popular template language that has actually been implemented in various programming languages. Using it, you can reuse templates in client or service segments. As you guessed, Mustache.php is implemented using PHP.

1

2

$m= newMustache_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.

18. Gaufrette – File system abstraction layer

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

useGaufretteFilesystem;

useGaufretteAdapterFtp asFtpAdapter;

useGaufretteAdapterLocal asLocalAdapter;

//Local file:

$adapter= newLocalAdapter('/var/media');

//Optionally use an FTP adapter

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

//Initialize the file system

$filesystem= newFilesystem($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 will be added later.

19. 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 only need to learn an API and deal with various payment processors. Here is an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

useOmnipayCreditCard;

use OmnipayGatewayFactory;

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

$gateway->setApiKey('abc123');

$formData= [ 'number' => '4111111111111111', 'expiryMonth'=> 6, 'expiryYear'=> 2016];

$response= $gateway->purchase(['amount'=> 1 000, 'card '=> $formData]);

if($response->isSuccessful()) {

/ /Payment successful: update database

print_r($response);

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

//jump Go to an off-site payment gateway

$response->redirect();

} else{

//Payment failed: Display information to customers

exit($response->getMessage());

}

Using the same consistent API, it is easy to support multiple Payment processor, or switch if needed.

20. Upload – Handling file uploads

Upload is a library that simplifies file uploading and verification. When uploading a form, this library verifies the file type and size.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

$storage= newUploadStorageFileSystem( '/path/to/directory');

$file= newUploadFile('foo', $storage);

//Verify file upload

$file->addValidations(array(

//Make sure the file type is "image /png"

​​​​newUploadValidationMimetype('image/png'),

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

​​​newUploadValidationSize('5M')

));

//Attempting to upload a file

try{

//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 filtering library that protects your code from XSS attacks through powerful whitelisting and aggregation analysis. It also ensures that the output markup conforms to the standard. (The source code is on github)

1

2

3

4

5

require_once'/path/to/H TMLPurifier.auto.php' ;

$config= HTMLPurifier_Config::createDefault();

$purifier= newHTMLPurifier($config);

$clean_html= $purifier->purify($dirty_html);

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

22. ColorJizz-PHP – Color manipulation library

ColorJizz is a simple library with which you can convert different color formats and do simple color operations

1

2

3

4

5

6

7

useMischiefCollectiveColorJizzFormatsHex;

$red_hex= newHex(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 major color formats

23. PHP Geo – Geolocation Positioning Library

phpgeo is a simple library for calculating geography Highly accurate distances between coordinates. For example:

1

2

3

4

5

6

7

8

useLocationCoordinate;

use LocationDistanceVincenty;

$coordinate1= newCoordinate(19.820664, -155.468066); // Mauna Kea Summit

$coordinate2 = new Coordinate(20.709722, -156.253333); // Haleakala Summit

$calculator= newVincenty();

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

It will work well in apps that use geolocation data. You can try translating the HTML5 Location API, Yahoo's API (or both, as we did in the weather web app tutorial) to get the coordinates.

24. ShellWrap – Beautiful command line wrapper

With the ShellWrap library, you can use powerful Linux/Unix command line tools in PHP code.

When an exception occurs on the command line, this library throws an exception so you can react to it in time. It can also allow you to pipe the output of one command as the input of another command to achieve greater flexibility.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

2 7

require'ShellWrap.php ';

useMrRioShellWrap assh;

//List all files under the current file

echosh::ls();

//Check out a git branch

sh::git('checkout', 'master');

//You can also pipe the output of one command to another command

//The following tracks the position through curl, and then filters the 'html' pipe through grep Download example.com website

echosh::grep('html', sh::curl('http://example.com', 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 an exception was thrown because the file did not exist)

try{

​​​sh::rm('file. html');

} catch(Exception $e) {

                                                          '; }

The above introduces 24 libraries that PHP developers should know, including relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn