PHP 徹底面向對象風格的 Array 和 String 編程

PHP 語言中操做字符串和數組通常使用 str_*array_* 的系列函數,這些函數因爲歷史緣由,命名和參數順序風格不統一,廣爲開發者詬病,PHP 語言標準庫中暫未提供 OO 風格的 ArrayString 類庫,開發者使用起來不是很便利,在 Swoole 中咱們提供了一 swoole_arrayswoole_string 對字符串和數組操做進行了面向對象封裝,能夠使用徹底面向對象風格進行 ArrayString 編程。php

使用方法

  • Swoole 項目:可直接使用
  • Swoole 項目,使用 composer require swoole/library 引入

絕大部分方法提供了鏈式風格支持,能夠一路使用 -> 編寫邏輯。底層類庫使用了 declare(strict_types=1) 強類型,使用 phpstorm 工具時,能夠實現徹底自動提示和自動完成。java

微信截圖_20200621154143.png

建立數組

$array1 = swoole_array(['hello', 'world']);
$array2 = swoole_array(['hello' => 1, 'world' => 2]);
$array3 = swoole_array_list('hello', 'world', 'swoole', 'php');

建立字符串

// Bytes 字符串
$string1 = swoole_string('hello world, php java, swoole');
// 寬字符串
$string2 = swoole_mbstring('我是中國人');
// 返回 5
$string2->length();

獲取元素

// 獲取
$value1 = $array1->get(0);
$value2 = $array2->get('hello');

// 數組的第一個元素
$first = $array->first();
// 數組的最後一個元素
$last = $array->last();

增長/設置

// 設置
$array1->set(0, 'swoole');
$array2->set('world', 9);
// 在末尾追加
$array1->pushBack('java');
// 在頭部插入
$array1->pushFront('go');
// 在中間 offset 2 插入
$array1->insert(2, 'rust');

連續追加

$array1->append('rust')->append('c++')->append('swift', 'kotlin');
$array2->set('rust', 99)->set('c++', 88)->set('kotlin', 77);

刪除

// 按 key 刪除
$array1->delete(0);
$array2->delete('worker');
// 按 value 刪除
$array1->remove('hello');

包含

使用contains()方法能夠判斷數組或字符串中是否包含某個元素。c++

$array1->contains('java');
$string1->contains('php');

使用startsWith()endsWith()方法判斷字符串開頭和結尾是否爲指定的值。git

$str = swoole_string('php and swoole');

$str->startsWith('php'); //true
$str->startsWith('java'); //false
$str->endsWith('swoole'); //true
$str->endsWith('golang'); //false

搜索

// 查找數組中是否有某個值,存在則返回其 key
$key = $array1->search('java');

結合使用

StringArray能夠結合使用。github

$s = '11, 33, 22, 44,12,32,55,23,19,23';

$data = swoole_string($s)
    ->split(',')
    ->each(fn(&$item) => $item = intval($item))
    /* < 7.4 : function (&$item){ $item = intval($item);} */
    ->sort()
    ->unique()
    ->join('-')
    ->contains('-44-');

var_dump($data);
  • 首先構建了一個字符串對象
  • 使用split按照,分割爲數組
  • 遍歷並應用$fn函數將元素轉換爲整數
  • 排序
  • 去重
  • 將數組元素使用-組合成爲字符串
  • 判斷字符串對象中是否包含-44-

類型推斷

swoole_array對象元素操做時,底層會自動判斷它的類型,若是爲數組或字符串,底層會遞歸封裝。golang

$array = swoole_array_list(['hello' => 'swoole']);
$array->get(0)->get('hello')->contains('swoole');

性能測試

底層實現其實就是基於str_array_相關函數進行面向對象封裝,沒有過多性能損耗,僅爲一次method調用開銷。咱們編寫了嚴格的單測覆蓋到每一個API,保證其可靠性。shell

性能方面,使用String::contains()執行100萬次,與直接運行 php strpos差距不大。編程

swoole_string: 0.059892892837524s, php_string: 0.033510208129883s

源代碼

若是您對此項目感興趣,能夠參與到咱們的開發工做中,期待您的 Pull Requestswift

相關文章
相關標籤/搜索