2

underscore是前端常用的javascript库,最近无意中发现原来它还有PHP的移植

基本介绍

绝大部分函数都移植过来了。underscore.js用的是_,可是这个在PHP中已经用来表示gettext()了,所以改成了__,双下划线。

使用很简单:

__(array(1, 2, 3))->map(function($n) { return $n * 3; });

或者,如果你偏爱静态风格:

__::map(array(1, 2, 3), function($n) { return $n * 3; });

结果:

Array
(
    [0] => 3
    [1] => 6
    [2] => 9
)

安装

composer

一般用Composer安装:

"anahkiasen/underscore-php" : "dev-master"

Laravel

如果用Laravel框架,可以用artisan

artisan bundle:install underscore

然后在bundles文件中加入这行:

'underscore' => array('auto' => true),

include/require

如果你这么传统……那当然也是可以的。

函数一览

绝大部分都移植过来了:

Collections

each, map, reduce, reduceRight, detect, select, reject, all, any, includ, invoke, pluck, max, min, groupBy, sortBy, sortedIndex, toArray, size

Arrays

first, rest, last, compact, flatten, without, uniq, union, intersection, difference, zip, indexOf, lastIndexOf, range

Functions

memoize, throttle, once, after, wrap, compose

Objects

keys, values, functions, extend, defaults, clon, tap, isEqual, isEmpty, isObject, isArray, isFunction, isString, isNumber, isBoolean, isDate, isNaN, isNull

Utility

identity, times, mixin, uniqueId, template

Chaining

chain, value

我自己更习惯写原生PHP。不过这个库可以帮助从前端转过来的同学,所以这里和大家分享一下。


Lvye
2k 声望140 粉丝