63

PHP 函数的 JavaScript 实现

module.exports = function array_sum (array) { // eslint-disable-line camelcase
  //  discuss at: http://locutus.io/php/array_sum/
  // original by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Nate
  // bugfixed by: Gilbert
  // improved by: David Pilia (http://www.beteck.it/)
  // improved by: Brett Zamir (http://brett-zamir.me)
  //   example 1: array_sum([4, 9, 182.6])
  //   returns 1: 195.6
  //   example 2: var $total = []
  //   example 2: var $index = 0.1
  //   example 2: for (var $y = 0; $y < 12; $y++){ $total[$y] = $y + $index }
  //   example 2: array_sum($total)
  //   returns 2: 67.2
  var key
  var sum = 0
  // input sanitation
  if (typeof array !== 'object') {
    return null
  }
  for (key in array) {
    if (!isNaN(parseFloat(array[key]))) {
      sum += parseFloat(array[key])
    }
  }
  return sum
}

Underscore.js 的 PHP 版

function __($item=null) {
  $__ = new __;
  if(func_num_args() > 0) $__->_wrapped = $item;
  return $__;
}

自动生成 gitignore 文件

https://www.gitignore.io/api/laravel
# Created by https://www.gitignore.io/api/laravel

### Laravel ###
vendor/
node_modules/
npm-debug.log

# Laravel 4 specific
bootstrap/compiled.php
app/storage/

# Laravel 5 & Lumen specific
public/storage
public/hot
storage/*.key
.env.*.php
.env.php
.env
Homestead.yaml
Homestead.json

# Rocketeer PHP task runner and deployment package. https://github.com/rocketeers/rocketeer
.rocketeer/

# End of https://www.gitignore.io/api/laravel

爬虫组件

composer global require slince/spider *@dev
use Slince\Spider\Spider;

$spider = new Spider();
$spider->run('http://www.baidu.com');

简单、 灵活、强大的 PHP 采集工具

use QL\QueryList;
//采集某页面所有的图片
$data = QueryList::Query('http://cms.querylist.cc/bizhi/453.html',array(
    //采集规则库
    //'规则名' => array('jQuery选择器','要采集的属性'),
    'image' => array('img','src')
    ))->data;
//打印结果
print_r($data);

//采集某页面所有的超链接
//可以先手动获取要采集的页面源码
$html = file_get_contents('http://cms.querylist.cc/google/list_1.html');
//然后可以把页面源码或者HTML片段传给QueryList
$data = QueryList::Query($html,array(
    'link' => array('a','href')
    ))->data;
//打印结果
print_r($data);
在线测试采集并查看采集结果 http://querylist.cc/page-Querytest.html

在线测试代码

clipboard.png

$array=[
    ['name'=>'张三','age'=>'23'],
    ['name'=>'李四','age'=>'64'],
    ['name'=>'王五','age'=>'55'],
    ['name'=>'赵六','age'=>'66'],
    ['name'=>'孙七','age'=>'17'],
];
$sort = array(
    'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
    'field'     => 'age',       //排序字段
);
$arrSort = array();
foreach($array as $uniqid => $row){
    foreach($row AS $key=>$value){
        $arrSort[$key][$uniqid] = $value;
    }
}
array_multisort($arrSort[$sort['field']], constant($sort['direction']), $array);
print_r($array);

中文转拼音工具

//https://hellogithub.com/category/PHP%20%E9%A1%B9%E7%9B%AE/
use Overtrue\Pinyin\Pinyin;
$pinyin = new Pinyin();
$pinyin->convert('带着希望去旅行,比到达终点更美好');
// ["dai", "zhe", "xi", "wang", "qu", "lv", "xing", "bi", "dao", "da", "zhong", "dian", "geng", "mei", "hao"]

$pinyin->convert('带着希望去旅行,比到达终点更美好', PINYIN_UNICODE);
// ["dài","zhe","xī","wàng","qù","lǚ","xíng","bǐ","dào","dá","zhōng","diǎn","gèng","měi","hǎo"]

$pinyin->convert('带着希望去旅行,比到达终点更美好', PINYIN_ASCII);
//["dai4","zhe","xi1","wang4","qu4","lv3","xing2","bi3","dao4","da2","zhong1","dian3","geng4","mei3","hao3"]

美化 curl

$ git clone https://github.com/talhasch/php-httpstat
$ cd php-httpstat
$ cp httpstat.php /usr/local/bin/httpstat
$ chmod +x /usr/local/bin/httpstat
$ httpstat http://www.google.com

在线正则表达式测试

clipboard.png

在线测试 redis

clipboard.png

在线练习 git

clipboard.png

检测 PHP 应用的代码复杂度

composer global require 'phploc/phploc=*'
$ phploc src
phploc 4.0.0 by Sebastian Bergmann.

Directories                                          3
Files                                               10

Size
  Lines of Code (LOC)                             1882
  Comment Lines of Code (CLOC)                     255 (13.55%)
  Non-Comment Lines of Code (NCLOC)               1627 (86.45%)
  Logical Lines of Code (LLOC)                     377 (20.03%)
    Classes                                        351 (93.10%)
      Average Class Length                          35
        Minimum Class Length                         0
        Maximum Class Length                       172
      Average Method Length                          2
        Minimum Method Length                        1
        Maximum Method Length                      117
    Functions                                        0 (0.00%)
      Average Function Length                        0
    Not in classes or functions                     26 (6.90%)

php http 请求工具

$response = Zttp::withHeaders(['Fancy' => 'Pants'])->post($url, [
    'foo' => 'bar',
    'baz' => 'qux',
]);

$response->json();
// => [
//  'whatever' => 'was returned',
// ];

任务管理

composer global require consolidation/robo
class RoboFile {
/**
 * Each public method is a command in runner
 * parameters are arguments in console
 *
 * use './robo test' to run tests on a project
 */
function test($pathToSelenium = '~/selenium.jar')
{
    // starts PHP server in background
    $this->taskPhpServer(8000)
        ->background()
        ->dir('web')
        ->run();

    // launches Selenium server
    $this->taskExec('java -jar '.$pathToSelenium)
        ->background()
        ->run();

    // runs PHPUnit tests
    $this->taskPHPUnit()
        ->run();
}

phpstorm 技巧

clipboard.png

php ai

composer require php-ai/php-ml
require_once 'vendor/autoload.php';

use Phpml\Classification\KNearestNeighbors;

$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];

$classifier = new KNearestNeighbors();
$classifier->train($samples, $labels);

echo $classifier->predict([3, 2]);
// return 'b'

PHP driver for FFMpeg

$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video
    ->filters()
    ->resize(new FFMpeg\Coordinate\Dimension(320, 240))
    ->synchronize();
$video
    ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(10))
    ->save('frame.jpg');
$video
    ->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
    ->save(new FFMpeg\Format\Video\WMV(), 'export-wmv.wmv')
    ->save(new FFMpeg\Format\Video\WebM(), 'export-webm.webm');

编码格式化工具

//http://cs.sensiolabs.org/  composer  global require fabpot/php-cs-fixer
//wget http://get.sensiolabs.org/php-cs-fixer.phar -O php-cs-fixer
curl http://get.sensiolabs.org/php-cs-fixer.phar -o php-cs-fixer
sudo chmod a+x php-cs-fixer
sudo mv php-cs-fixer /usr/local/bin/php-cs-fixer
# 格式化目录 如果是当前目录的话可以省略目录
php-cs-fixer fix /path/to/dir
# 格式化文件
php-cs-fixer.phar fix /path/to/file
//cat foo.php | php-cs-fixer fix --diff -
#https://housanpai.com/articles/10

php medoo

composer require catfan/Medoo
// 如果你通过 composer 安装, 只需在项目的开始部分加上此代码即可自动加载。
require 'vendor/autoload.php';
 
// 或者你是下载 medoo.php 并放置到项目目录中,require 即可。
require  'medoo.php';
 
$database = new medoo([
    // 必须的
    'database_type' => 'mysql',
    'database_name' => 'name',
    'server' => 'localhost',
    'username' => 'your_username',
    'password' => 'your_password',
    'charset' => 'utf8',
 
    // [可选]
    'port' => 3306,
 
    // [可选] 表名前缀
    'prefix' => 'PREFIX_',
 
    // [可选] 连接的驱动选项,请阅读 http://www.php.net/manual/en/pdo.setattribute.php
    'option' => [
        PDO::ATTR_CASE => PDO::CASE_NATURAL
    ]
]);
 
$database->insert("account", [
    "user_name" => "foo",
    "email" => "foo@bar.com"
]);

在线文档分享工具

composer create-project showdoc/showdoc

php的ngrok客户端

比对两个数据库的表结构,并自动修正

git clone https://github.com/exinnet/mysqldiff.git
cd mysqldiff
vi config.php # config mysql connection info

php mysqldiff.php

cron

file_get_contents('https://hchk.io/e9ad1415-566c-40c9-9c97-a298d727ab68');

语法检测

composer require overtrue/phplint -vvv
use Overtrue\PHPLint\Linter;

$path = __DIR__ .'/app';
$exclude = ['vendor'];
$extensions = ['php'];

$linter = new Linter($path, $exclude, $extensions);

// get errors
$errors = $linter->lint();

//
// [
//    '/path/to/foo.php' => [
//          'error' => "unexpected '$key' (T_VARIABLE)",
//          'line' => 168,
//          'file' => '/path/to/foo.php',
//      ],
//    '/path/to/bar.php' => [
//          'error' => "unexpected 'class' (T_CLASS), expecting ',' or ';'",
//          'line' => 28,
//          'file' => '/path/to/bar.php',
//      ],
// ]

生成Material Design风格头像

// composer 
require(__DIR__ . "/vendor/autoload.php");
use Md\MDAvatars;

$Avatar = new MDAvatars('X', 512);
$Avatar->Output2Browser();
$Avatar->Save('./avatars/Avatar256.png', 256);

使用screw plus来保护php代码安全

一个最精简的php多进程控制库

$sf = new SimpleFork(2, 'my-process'); // 2代表子进程数, 'my-process'是进程的名字

$sf->master(function ($sf) {
    // 主进程的方法请包裹在master里
    while ($sf->loop(100)) { // 100为等待的毫秒数
        $sf->submit('http://www.google.cn/', function ($data) { // 使用submit方法将其提交到一个空闲的进程,如果没有空闲的,系统会自动等待
            echo $data;
        });
    }
})->slave(function ($url, $sf) {
    $sf->log('fetch %s', $url); // 使用内置的log方法,子进程的log也会被打印到主进程里
    return http_request($url);  // 直接返回数据,主进程将在回调中收到
});

A PHP MySQL PDO class similar to the the Python MySQLdb

$DB->query("SELECT * FROM fruit WHERE name=".$_GET['name']);

$DB->query("SELECT * FROM fruit WHERE name=? and color=?",array('apple','red'));
$DB->query("SELECT * FROM fruit WHERE name=:name and color=:color",array('name'=>'apple','color'=>'red'));
$DB->query("SELECT * FROM fruit WHERE name IN (?)",array('apple','banana'));

图片处理

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'https://avatars0.githubusercontent.com/u/5785188?v=3&s=460');
$response =  curl_exec($ch);
curl_close($ch);

$UploadAvatar = new ImageResize('String', $response);
$Result = $UploadAvatar->Resize(256, 'upload/avatar/large.png', 80);

Linux 图形化性能监视器

编写PHP代码片段终极机器人

clipboard.png

PHP 代码转 Python

def substr (self, s, start, length = None):
        """Returns the portion of string specified by the start and length 
        parameters.
        """
       if len(s) >= start:
            if start > 0:
                return False
            else:
                return s[start:]
        if not length:
            return s[start:]
        elif length > 0:
            return s[start:start + length]
        else:
            return s[start:length]

php部署工具

curl -LO https://deployer.org/deployer.phar
mv deployer.phar /usr/local/bin/dep
chmod +x /usr/local/bin/dep
composer require deployer/deployer

公众号:苏生不惑

clipboard.png


苏生不惑
18.9k 声望1.9k 粉丝