自定义短代码解析器

时间:2016-07-01 13:43:00

标签: php laravel shortcode

我正在尝试为PHP中的短代码创建自定义解析器,但我需要使用php函数(或者甚至是php库)的指示。请注意,我使用的是Laravel 5,因此也欢迎使用包。

例如,我有一个这种格式的字符串:

Hello {{user.first_name}}, your ID is {{user.id}}

我有一个包含这些参数的$user对象。我想检查字符串中是否存在字符串中的所有短代码参数,如果没有,我想返回错误,如果是,我想返回解析后的字符串,该字符串等于:

Hello John, your ID is 123.

更新

请注意,我正在构建REST API,这将用于自动电子邮件系统。我需要控制器中的字符串中的结果,所以我可以在返回json响应之前在我的邮件函数中使用它。

1 个答案:

答案 0 :(得分:2)

根据您的模板样式Mustache.php是实现目标的正确库。

使用Composer。将mustache/mustache添加到项目的composer.json:

{
    "require": {
        "mustache/mustache": "~2.5"
    }
}

<强>用法:

if(isset($user->first_name) && isset($user->id)) {
    $m = new Mustache_Engine;
    return $m->render("Hello {{first_name}}, your ID is {{id}}", $user);
    //will return: Hello John, your ID is 123.
}else {
    //trigger error
}

更新1:

如果您的数据对象是Eloquent实例,则可以使用以下类在缺少变量的情况下自动抛出错误:

class MustacheData {

  private $model;

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

  public function __isset($name) {
    if (!isset($this->model->{$name})) {
      throw new InvalidArgumentException("Missing $name");
    }

    return true;
  }

  public function __get($name) {
    return $this->model->{$name};
  }
}

<强>用法:

try {
    $m = new Mustache_Engine;
    return $m->render("Hello {{first_name}}, your ID is {{id}}", new MustacheData($user));
}catch(InvalidArgumentException $e) {
    //Handle the error
}