为什么在角色和权限中使用了刀片指令?在这里解释下面的例子

时间:2018-05-09 10:21:02

标签: php laravel-5

我的任务是在内置应用程序中添加新功能,最后我会得到一段代码。我不知道它是如何工作的。 在AppServiceProvider.php上

 Blade::directive('hasRole', function ($expression) {
            $exp=explode(",",$expression);
            return "<?php if(Auth::user()->hasPermission($exp[0],$exp[1])): ?>";
        });

在刀片上:

@hasRole('travel_calendar','view')
        <button class="btn btn-space btn-default btn-big tactive" id="travel_menu_cal" ><i class="icon mdi mdi-calendar"></i> Calendar</button>
        @endHasRole

视图在此代码中的作用也是如此。 有人在那里向我解释代码。

1 个答案:

答案 0 :(得分:0)

从上到下,内联评论:

// Declare a custom function with name 'hasRole' that can be used in Blade files
Blade::directive('hasRole', function ($expression) {
    // If there are comma's in the expression, split those and dump the resulting strings in an array
    $exp=explode(",",$expression);
    // Return some php code that evaluates to pseudocode:
        // if user has permission to expression
    return "<?php if(Auth::user()->hasPermission($exp[0],$exp[1])): ?>";
});

// Use defined function, expression exists of two string: travel_calendar and view
@hasRole('travel_calendar','view')
    <button class="btn btn-space btn-default btn-big tactive" id="travel_menu_cal" ><i class="icon mdi mdi-calendar"></i> Calendar</button>
@endHasRole

整个事情基本上都是这样评估的:

If user has permission to view travel_calendar
    Then show button