Khi đã lập trình website thì một điều chắc chắn là bạn phải sử dụng lại các thư viện của người khác đã viết để tiết kiệm thời gian và lỗi phát sinh.
Có rất nhiều thư viện PHP hữu ích phát hành mỗi ngày, và với sự giúp đỡ của Composer và Github, chúng ta dễ dàng khám phá và sử dụng. Dưới đây là một số thư viện thú vị nhất.
1. Dispatch – Micro Framework
Dispatch là một PHP framework nhỏ. Nó không cung cấp cho bạn một thiết lập MVC đầy đủ, nhưng có thể định nghĩa quy định URL và phương pháp tốt hơn ứng dụng của bạn. Hoàn hảo cho các API, các trang web đơn giản hoặc nguyên mẫu:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| // include the libraryinclude 'dispatch.php';// define your routesget('/greet', function () { // render a view render('greet-form');});// post handlerpost('/greet', function () { $name = from($_POST, 'name'); // render a view while passing some locals render('greet-show', array('name' => $name));});// serve your sitedispatch(); |
2. Klein – Lightning fast router for PHP
Klein là một thư viện định tuyến (routing) nhẹ dành cho PHP 5.3 +. Nó có nhiều hơn một chút cú pháp, nhưng là khá nhanh. Đây là một ví dụ:
1
2
3
| respond('/[:name]', function ($request) { echo 'Hello ' . $request->name;}); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| 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 placerespond('/posts/[create|edit:action]?/[i:id]?', function ($request, $response) { switch ($request->action) { // do something }}); |
3. Ham – Routing Library with Caching
Ham cũng là một khuôn khổ định tuyến nhẹ nhưng nó sử dụng bộ nhớ đệm cho nhiều hơn tăng tốc độ. Nó đạt được điều này bằng cách cache bất cứ điều gì I/O liên quan trong XCache/APC. Đây là một ví dụ:
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 – Asset Management
Assetic là khuôn khổ quản lý tài sản cho PHP. Nó kết hợp và làm gọn CSS/JS của bạn. Sau đây là cách nó được sử dụng:
1
2
3
4
5
6
7
8
9
10
11
| 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 dumpedecho $js->dump(); |
5. ImageWorkshop – Image Manipulation with Layers
ImageWorkshop là một thư viện mã nguồn mở cho phép bạn thao tác hình ảnh với các lớp. Với nó, bạn có thể thay đổi kích thước, cắt xén, làm cho hình thu nhỏ, thêm thủy ấn và nhiều hơn nữa. Đây là một ví dụ:
1
2
3
4
5
6
7
8
9
10
11
| // 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'); $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; |
6. Snappy – Snapshot/PDF Library
Snappy là một thư viện PHP5 cho phép bạn chụp những bức ảnh hoặc file PDF của URL hoặc các tài liệu HTML. Nó phụ thuộc vào wkhtmltopdf a> nhị phân, trong đó có sẵn trên Linux, Windows và OSX. Bạn sử dụng nó như thế này:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| require_once '/path/to/snappy/src/autoload.php'; use Knp\Snappy\Pdf; // Initialize the library with the// path to the wkhtmltopdf binary:$snappy = new Pdf('/usr/local/bin/wkhtmltopdf'); // Display the resulting 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'); |
7. Idiorm – Lightweight ORM Library
Idiorm là một thư viện ORM nhẹ và một người xây dựng truy vấn thông thạo cho PHP5 được xây dựng trên đầu trang của PDO. Với nó, bạn có thể quên viết tẻ nhạt của 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( 'user.id', '=', 'tweet.user_id' )) ->where_equal('user.username', 'j4mie') ->find_many();foreach ($tweets as $tweet) { echo $tweet->text;} |
8. Underscore – PHP’s Utility Belt
Underscore là một cổng của Underscore.js a> - vành đai tiện ích cho các ứng dụng JavaScript. Phiên bản PHP không thất vọng và đã hỗ trợ cho gần như tất cả các chức năng của bản gốc. Một số ví dụ:
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) |
9. Requests – Easy HTTP Requests
Requests is a library that makes it easy to issue HTTP requests. If you are like me, and can never seem to remember the various options passed to Curl, this is for you: là một thư viện làm cho nó dễ dàng để đưa ra các yêu cầu HTTP. Nếu bạn không bao giờ có thể nhớ các tùy chọn khác nhau thông qua Curl, điều này là dành cho bạn:
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) "[…]" |
10. Buzz – Simple HTTP Request Library
Buzz \ là một thư viện PHP cho các yêu cầu HTTP. Đây là một ví dụ:
1
2
3
4
5
6
7
8
| $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; |
11. Goutte – Web Scraping Library
Goutte là một thư viện để quét trang web và giải nén dữ liệu. Nó cung cấp một API tốt đẹp mà làm cho nó dễ dàng để lựa chọn các yếu tố cụ thể từ các trang từ xa.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| require_once '/path/to/goutte.phar'; use Goutte\Client; $client = new Client();$crawler = $client->request('GET', 'http://www.symfony-project.org/'); // Click on links: $link = $crawler->selectLink('Plugins')->link();$crawler = $client->click($link); // Extract data with a CSS-like syntax: $t = $crawler->filter('#data')->text(); echo "Here is the text: $t"; |
12. Carbon – DateTime Library
Carbon là một API mở rộng đơn giản cho ngày và giờ. Nó giúp tăng cường các một số phương pháp hữu ích để làm việc với ngày và thời gian. Ví dụ:
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');// comparisons are always done in UTCif (Carbon::now()->gte($endOfWorld)) { die();}if (Carbon::now()->isWeekend()) { echo 'Party!';}echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago' |
13. Ubench – Micro Benchmarking Library
Ubench là một thư viện nhỏ cho chuẩn mã PHP của bạn. Nó theo dõi thời gian thực hiện và sử dụng bộ nhớ. Đây là một ví dụ:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| use Ubench\Ubench;$bench = new Ubench;$bench->start();// Execute some code$bench->end();// Get elapsed time and memoryecho $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); // memory peak in bytesecho $bench->getMemoryPeak(false, '%.3f%s'); // 152B or 90.152Kb or 15.234Mb// Returns the memory usage at the end markecho $bench->getMemoryUsage(); // 152B or 90.00Kb or 15.23Mb |
14. Validation – Input Validation Engine
Validation tuyên bố là công cụ xác nhận tuyệt vời nhất từng được tạo ra cho PHP. Nhưng nó có thể cung cấp được gì?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| 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'; // Validate its attributes in a single chain: $userValidator = v::attribute('name', v::string()->length(1,32)) ->attribute('birthdate', v::date()->minimumAge(18)); $userValidator->validate($user); //true |
15. Filterus – Filtering Library
Filterus là một thư viện bộ lọc, nhưng nó có thể không chỉ xác nhận, nhưng cũng đầu vào bộ lọc để phù hợp với một mô hình định sẵn. Đây là một ví dụ:
1
2
3
4
5
| $f = Filter::factory('string,max:5');$str = 'This is a test string'; $f->validate($str); // false$f->filter($str); // 'This ' |
16. Faker – Fake Data Generator
Faker là một thư viện PHP tạo ra các dữ liệu giả mạo cho bạn. Nó tiện dụng khi bạn cần phải một cơ sở dữ liệu thử nghiệm hoặc tạo ra các dữ liệu mẫu cho ứng dụng web của bạn. Nó cũng rất dễ dàng để sử dụng:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| // require the Faker autoloaderrequire_once '/path/to/Faker/src/autoload.php';// use the factory to create a Faker\Generator instance$faker = Faker\Factory::create();// generate data by accessing propertiesecho $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 ... |
17. Mustache.php – Elegant Templating Library
Mustache là một ngôn ngữ khuôn mẫu phổ biến mà có thể triển khai trong thực tế tất cả các ngôn ngữ lập trình. Điều này cung cấp cho bạn những lợi ích mà bạn có thể sử dụng lại mẫu của bạn trong cả khách hàng và phía máy chủ. Mustache.php a> là một thực hiện sử dụng - bạn đoán nó - PHP:
1
2
| $m = new Mustache_Engine;echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!" |
18. Gaufrette – File System Abstraction Layer
Gaufrette là một thư viện PHP5 cung cấp một lớp trừu tượng hệ thống tập tin. Nó làm cho nó có thể làm việc với các tập tin địa phương, máy chủ FTP, Amazon S3 và nhiều hơn nữa trong cùng một cách. Điều này cho phép bạn phát triển các ứng dụng của bạn mà không cần phải biết làm thế nào bạn sẽ truy cập các tập tin của bạn trong tương lai.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| 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); // Initialize the filesystem:$filesystem = new Filesystem($adapter); // Use it: $content = $filesystem->read('myFile');$content = 'Hello I am the new content';$filesystem->write('myFile', $content); |
19. Omnipay – Payment Processing Library
Omnipay là một thư viện xử lý các thanh toán cho PHP. Nó có một API rõ ràng và nhất quán và hỗ trợ hàng chục cổng thanh toán. Với thư viện này, bạn chỉ cần tìm hiểu một API và làm việc với nhiều bộ xử lý thanh toán. Đây là một ví dụ:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| 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());} |
20. Upload – For Handling File Uploads
Upload là một thư viện đơn giản hóa tập tin tải lên và xác nhận. Khi một mẫu được gửi, thư viện có thể kiểm tra các loại tập tin và kích thước:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| $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 filetry { // Success! $file->upload();} catch (\Exception $e) { // Fail! $errors = $file->getErrors();} |
21. HTMLPurifier – HTML XSS Protection
HTMLPurifier (on github) là một thư viện lọc HTML để bảo vệ mã của bạn từ các cuộc tấn công XSS (CROSS SITE SCRIPTING). Nó cũng đảm bảo rằng các đánh dấu kết quả là tiêu chuẩn phù hợp.
1
2
3
4
5
| require_once '/path/to/HTMLPurifier.auto.php';$config = HTMLPurifier_Config::createDefault();$purifier = new HTMLPurifier($config);$clean_html = $purifier->purify($dirty_html); |
22. ColorJizz-PHP – Color Manipulation Library
ColorJizz là một thư viện nhỏ mà có thể chuyển đổi giữa các định dạng màu sắc khác nhau và làm phép tính đơn giản, màu sắc. Ví dụ:
1
2
3
4
5
6
7
| 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 |
23. PHP Geo – Geo Location Library
phpgeo là một thư viện đơn giản để tính toán khoảng cách giữa các tọa độ địa lý với độ chính xác cao. Ví dụ:
1
2
3
4
5
6
7
8
| use Location\Coordinate;use Location\Distance\Vincenty;$coordinate1 = new Coordinate(19.820664, -155.468066); // Mauna Kea Summit$coordinate2 = new Coordinate(20.709722, -156.253333); // Haleakala Summit$calculator = new Vincenty();$distance = $calculator->getDistance($coordinate1, $coordinate2); // returns 128130.850 (meters; ≈128 kilometers) |
24. ShellWrap – Beautiful Shell Wrapper
ShellWrap là thư viện cho phép bạn làm việc với các công cụ dòng lệnh Linux / Unix mạnh mẽ trong PHP thông qua một cú pháp đẹp:
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
27
28
29
| require 'ShellWrap.php';use \MrRio\ShellWrap as sh; // List all files in current direcho sh::ls(); // Checkout a branch in gitsh::git('checkout', 'master'); // You can also pipe the output of one command, into another// This downloads example.com through cURL, follows location, then pipes through grep to// filter for 'html'echo sh::grep('html', sh::curl('http://example.com', array( 'location' => true))); // Touch a file to create itsh::touch('file.html'); // Remove filesh::rm('file.html'); // Remove file again (this fails, and throws an exception because the file doesn't exist) try { sh::rm('file.html');} catch (Exception $e) { echo 'Caught failing sh::rm() call';} |
