dongshenjie3055 2016-07-01 13:43
浏览 19
已采纳

自定义短代码解析器

I am trying to create a custom parser for shortcodes in PHP, but I need directions on which php function (or maybe even php library) to use. Note that I am using Laravel 5, so packages are welcome too.

For example, I have a string in this format:

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

I have a $user object containing these parameters. I'd like to check if all shortcode parameters within the string exist in the object, if not, I'd like to return an error, and if yes, I'd like to return the parsed string which would equal to:

Hello John, your ID is 123.

UPDATE

Please note that I'm building a REST API and this would be used in an automated email system. I need the result in a string within the controller so I can use it in my mailing function before the json response is returned.

  • 写回答

1条回答 默认 最新

  • douzheng5717 2016-07-01 14:22
    关注

    According to your template style Mustache.php is the right library to achieve your goal.

    Use Composer. Add mustache/mustache to your project's composer.json:

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

    Usage:

    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
    }
    

    Update 1:

    If your data object is an Eloquent instance, you can use the following class to automatically throw errors in case of missing variables:

    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};
      }
    }
    

    Usage:

    try {
        $m = new Mustache_Engine;
        return $m->render("Hello {{first_name}}, your ID is {{id}}", new MustacheData($user));
    }catch(InvalidArgumentException $e) {
        //Handle the error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作