7.x 新特性之流畅的字符串操作

未匹配的标注

对于字符串的处理,链式操作要比一个个调用函数显得更加直观

<?php

// 直接使用
strlen(trim($str));

// 链式调用
$str = new Str(" abcde ");
echo $str->trim()->strlen();

之前提到过如何用 PHP 的重载来实现字符串函数的链式调用

<?php

class Str
{
    public $string;

    public function __construct($string)
    {
        $this->string = $string;
    }

    public function __call($method, $args)
    {
        if (!$args) {
            $args = $this->string;
        }

        $this->string = call_user_func($method, $args);

        return $this;
    }

    public function __toString() : string
    {
        return (string) $this->string;
    }
}

Laravel 最新版本在 Str 中也引入了链式调用,我们以获取模型的表名为例。

<?php

use Illuminate\Support\Str;

// 之前
Str::plural(Str::snake(class_basename('UserAddress'))); // user_addresses

// 现在
echo Str::of(class_basename('UserAddress'))->snake()->plural(); 
Str::of(class_basename('UserAddress'))->snake()->plural()->__toString(); 

等价于

<?php

$stringable = new Stringable(class_basename('UserAddress'));
$stringable->snake()->plural()->__toString();

具体实现很简单,of 方法返回一个 Stringable 实例,Stringable 实例只是对 Str 类的方法进行简单的封装,并返回新的自身实例

<?php

class Stringable
{
    use Macroable;

    public function camel()
    {
        return new static(Str::camel($this->value));
    }

}

更多使用示例。

将标题转化为 slug

<?php

Str::of('hello world')->start('Begin ')->slug()->__toString(); // begin-hello-world

将事件名转化为标题

Str::of('created_post')->slug(' ')->title(); // Created Post

模板替代

<?php

use Illuminate\Support\Str;
use Illuminate\Support\Stringable;

$stub = <<<stub
  class {{CLASS}}
  {
  }
  stub;

$className = 'User';

echo Str::of($stub)
          ->replace('{{CLASS}}', $className)
            ->start("<?php\n\n");

显示结果

<?php

class User
{
}

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~