2016-07-01 97 views
0

我想创建一个自定义PHP短代码解析器,但我需要使用哪个php函数(或者甚至是php库)的方向。请注意,我使用的是Laravel 5,所以也欢迎包装。自定义短代码解析器

例如,我在这个格式的字符串:

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

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

Hello John, your ID is 123. 

UPDATE

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

+0

可能,这可能是有帮助吗? http://stackoverflow.com/questions/28554946/laravel-echoing-object-property-after-checking-for-existence –

+2

你有没有考虑过使用[Twig](http://twig.sensiolabs.org/),可能是如果你只是将它用于变量,有点矫枉过正。 –

+0

@Alok,因为我看到这是针对刀片式...我需要在模型/控制器中解析此字符串,而不是在模板中。 – Skatch

回答

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 
} 
+0

这很酷,现在我需要找到一种使参数验证成为动态的方法,我希望能够使用多个对象中可用的所有参数,而不会使条件成为静态,但请根据输入字符串检查参数是否存在。这是胡言乱语吗?无论如何,这也解决了我的问题,如果没有其他选项提供,我会接受它。 – Skatch

+0

你的对象'$ user'的类型是什么? –

+0

所有使用的对象都是单行的雄辩结果('$ user = User :: find($ id)')。我觉得我需要澄清我以前的评论,这不是很清楚。我想要获取字符串中的所有shortcode用法,检查这些变量是否在提供的对象中可用,然后解析或返回错误。实际上,我需要一个包含字符串内所有短代码的数组,以便在渲染之前进行检查。 – Skatch