taylornetwork/variable-replacer

在定义的阶段替换字符串中的变量

1.0.1 2018-03-20 13:48 UTC

This package is auto-updated.

Last update: 2024-09-24 11:39:50 UTC


README

此包将替换字符串中的变量。它包括基于阶段替换的功能,这意味着您可以在同一字符串的不同时间替换多个变量。

安装

使用Composer安装

$ composer require taylornetwork/variable-replacer

默认选项

默认情况下,替换变量的语法是

'@stage{var}'

注意变量前没有 $ 符号。

使用方法

假设您有一个日志类,用于记录最近的活动,并且您想在创建任何模型时定义相同的信息,但想在描述中包含模型信息。

在这个例子中,我的基础模型类定义如下

// App\Models\Model.php

use Illuminate\Database\Eloquent\Model;

abstract class Model
{

    /**
     * All models will define what the model's name is
     *
     * @return string
     */
    abstract public funtion getNameAttribute();

    /**
     * Returns the model name
     *
     * @return string
     */
    public function getModelNameAttribute()
    {
        return class_basename(get_class($this));
    }
}

在观察者类中,您可以执行以下操作。

// App\Observers\BaseObserver.php

use TaylorNetwork\VariableReplacer\VariableReplacer;
use App\Models\Model;
use Some\Logger\Package\Logger;

class BaseObserver
{
    protected $descriptions = [
        'created' => 'A @entry{modelName} named @runtime{name} was created.',
    ];
    
    public function created(Model $model) 
    {
        $description = (new VariableReplacer)->stage('entry')
                                             ->replaceWith($model)
                                             ->parse($this->descriptions['created']);
      
        return (new Logger)->log($description);
    }
}

VariableReplacer 获取传递给 replaceWith 方法的整个 App\Models\Model $model 对象,因此所有方法都可以使用。

如果创建了一个名为 'John Smith'App\Models\Customer 模型,则将保存到数据库的 $description

'A Customer name @runtime{name} was created.'

当访问日志时,您可以使用 runtime 阶段通过替换器运行描述。

// App\Models\Log.php

use TaylorNetwork\VariableReplacer\VariableReplacer;
use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    public function getDescriptionAttribute()
    {
        return (new VariableReplacer)->stage('runtime')
                                     ->replaceWith($this->relatedModel)
                                     ->parse($this->attributes['description']);
    }
}

假设 'A Customer named @runtime{name} was created.' 被传递,返回的值将是

'A Customer named John Smith was created.'

注意

由于 VariableReplacer 获取传递给 replaceWith 方法的整个对象,如果您需要获取关系等,可以在它上面链式调用方法。

示例

(new VariableReplacer)->stage('runtime')
                      ->replaceWith($someModel)
                      ->parse('A @runtime{relatedModel->someRelation->someOtherMethod()} did something');