Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将多个参数传递给blade指令_Php_Laravel_Blade_Laravel 5.3_Laravel Blade - Fatal编程技术网

Php 将多个参数传递给blade指令

Php 将多个参数传递给blade指令,php,laravel,blade,laravel-5.3,laravel-blade,Php,Laravel,Blade,Laravel 5.3,Laravel Blade,我正在尝试创建一个blade指令来突出显示从搜索查询返回的一些单词 这是我的刀片指令: class AppServiceProvider extends ServiceProvider { public function boot() { Blade::directive('highlight', function($expression, $string){ $expressionValues = preg_split('/\s+/'

我正在尝试创建一个blade指令来突出显示从搜索查询返回的一些单词

这是我的刀片指令:

class AppServiceProvider extends ServiceProvider

{
    public function boot()
    {
        Blade::directive('highlight', function($expression, $string){

            $expressionValues = preg_split('/\s+/', $expression);

            foreach ($expressionValues as $value) {
                $string = str_replace($value, "<b>".$value."</b>", $string);
            }

            return "<?php echo {$string}; ?>";
        });
    }

    public function register()
    {
    }
}
 public function boot()
    {
        Blade::directive('varSet', function ($expr) {
            $array = json_decode($expr, true);

            $p = '<?php ';
            foreach ($array as $key => $val) {
                if (is_string($val)) {
                    $p .= "\$$key = isset(\$$key) && !empty(\$$key) ? \$$key : '$val'; ";
                } else {
                    $p .= "\$$key = isset(\$$key) && !empty(\$$key) ? \$$key : $val; ";
                }
            }
            $p .= '?>';

            return $p;
        });
    }
但是,这个埃罗斯在跟踪我:

Missing argument 2 for App\Providers\AppServiceProvider::App\Providers\{closure}()

如何解决它?

我想你只能传递一个参数。这并不漂亮,但您可以将参数作为数组传递,如下所示:

@highlight(['expression' => 'ho', 'string' => 'house'])
所以你的指令可能是

class AppServiceProvider extends ServiceProvider

{
    public function boot()
    {
        Blade::directive('highlight', function($array){

            $expressionValues = preg_split('/\s+/', $array['expression']);

            foreach ($expressionValues as $value) {
                $array['string'] = str_replace($value, "<b>".$value."</b>", $array['string']);
            }

            return "<?php echo {$array['string']}; ?>";
        });
    }

    public function register()
    {
    }
}
类AppServiceProvider扩展了ServiceProvider
{
公共函数boot()
{
刀片::指令('highlight',函数($array){
$expressionValues=preg_split('/\s+/',$array['expression']);
foreach($expressionValues作为$value){
$array['string']=str_replace($value,“$value.”,$array['string']);
}
返回“”;
});
}
公共职能登记册()
{
}
}
在这里找到它:

Blade::指令('highlight',函数($arguments){
列表($arg1,$arg2)=分解(',',str_replace(['(','),'','','','','','',参数));
$expressionValues=preg_split('/\s+/',$arg1);
$output=“”;
foreach($expressionValues作为$value){
$output.=str_replace($value,“$value.”,$arg2);
}
返回“”;
});
在刀片模板中:

@custom('param1', 'param2', 'param3')

对于关联数组,eval()可能是最简单的。但是它的使用被宣传为危险的,因为它就像你打开一个洞,一根针来执行代码。同时eval()在运行时执行,它将要执行的代码存储在数据库中(缓存[它的意思是缓存已编译的字节码])。这是额外的开销,因此性能将受到影响。这是一篇关于这个主题的好文章[没有读到或涉及到细节])

好吧,我可能已经抓住你了,在服务器服务性能方面没有性能差异,因为视图是缓存的,只有在您更改视图时才会生成。指令被转换为php代码,并在另一个进程中被缓存。(您可以在存储/framework/views中找到生成的视图)

所以

但是,我们不能传递变量。例如:
@指令([“s”=>$var])
如果我们使用eval$var将在指令功能范围内未定义。(别忘了,指令只是一种漂亮地生成tempalte的方法,并且可以改变丑陋(不是真的丑陋)php代码转换成这样的指令。事实上,它是相反的,我们正在将漂亮的指令转换成最终将执行的php代码。您在这里所做的一切就是生成、构建、编写表达式,从而形成最终的php页面或文件。)

您可以改为以这种方式传递变量 [“s”=>“$var”],因此它将通过eval。然后在return语句中,使用以下示例:

return "<?php echo ".$array['s'].";?>";
下面是一个我需要这样做的示例: 我们的目标是实现自动化

@php
    $logo = !empty($logo) ? $logo : 'logo';
    $width = !empty($width) ? $width : 'logo';
    //...    // wait i will not always keep doing that ! h h
@endphp // imaging we do that for all different number of view components ...
所以我写了这个指令:

class AppServiceProvider extends ServiceProvider

{
    public function boot()
    {
        Blade::directive('highlight', function($expression, $string){

            $expressionValues = preg_split('/\s+/', $expression);

            foreach ($expressionValues as $value) {
                $string = str_replace($value, "<b>".$value."</b>", $string);
            }

            return "<?php echo {$string}; ?>";
        });
    }

    public function register()
    {
    }
}
 public function boot()
    {
        Blade::directive('varSet', function ($expr) {
            $array = json_decode($expr, true);

            $p = '<?php ';
            foreach ($array as $key => $val) {
                if (is_string($val)) {
                    $p .= "\$$key = isset(\$$key) && !empty(\$$key) ? \$$key : '$val'; ";
                } else {
                    $p .= "\$$key = isset(\$$key) && !empty(\$$key) ? \$$key : $val; ";
                }
            }
            $p .= '?>';

            return $p;
        });
    }
为什么这个表格有效?它作为字符串模板传递,如下所示

"""
{\n
    "logo": "logo",\n
    "width": 78,\n
    "height": 22\n
}
"""
为了在模板中使用变量,将它们作为字符串传递,如“$var”,与我们对eval所做的相同

对于从[''=>''进行解析,..]格式可能是eval()是最佳选择。请记住,这是在模板生成时完成的,模板生成将在稍后缓存,并且不会更新,直到我们再次进行更改。记住不要在返回中使用eval();指令指令。(仅当您的申请需要时)

仅适用于多个参数,而不是数组: 这样的函数可以完成以下任务:

 public static function parseMultipleArgs($expression)
{
    return collect(explode(',', $expression))->map(function ($item) {
        return trim($item);
    });
}

这将评估为

<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter(["name" => $user->name, .......]); ?>


所以一切都会好起来的。我举了一个例子,我们使用一个函数,你可以把所有的逻辑。指令只是以更漂亮的方式编写视图的一种方式。它还允许预视图处理和生成。安静很好。

在blade指令函数上接收到的值是一个sting,因此,您必须解析以获取值:

刀片

@date($date,'d-M-Y')

AppServiceProvider

Blade::directive('date', function ($str) {
  // $str = "$date, 'd-M-Y'";
  $data = explode(',',str_replace(' ', '', $str));
  //$data = ["$date", "'d-M-Y'"]
  $date = $data[0];
  $format = $data[1];
  return "<?= date_format(date_create($date), $format) ?>";
});
Blade::指令('date',函数($str){
//$str=“$date,'d-M-Y'”;
$data=explode(',',str_replace(',,$str));
//$data=[“$date”、“'d-M-Y'”]
$date=$data[0];
$format=$data[1];
返回“”;
});

我在寻找这个精确的解决方案,然后在阅读了所有内容后决定尝试一些不同的方法,最终找到了您和我都在寻找的解决方案

不需要JSON解决方法、分解、关联数组等。。。除非你以后想要更复杂的功能

因为Blade只是写出PHP代码以便稍后进行解释,所以您在@highlight指令中放入的内容都是将在稍后进行解释的字符串格式的PHP代码

该做什么:

Blade::directive("do", function ($expr) {
    return "<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter($expr); ?>
});
if(!function_exists('highlight')){

    function highlight($expression, $string){
        $expressionValues = preg_split('/\s+/', $expression);

        foreach ($expressionValues as $value) {
            $string = str_replace($value, "<b>".$value."</b>", $string);
        }

        return $string;
    }
}
Blade::directive('highlight', function ($passedDirectiveString){
        return "<?php echo highlight($passedDirectiveString);?>";
    });
<div>
    @highlight('ho', 'house')
</div>
创建并注册一个可以在整个应用程序中调用的助手函数。然后在blade指令中使用helper函数

//view.blade.php
@component('my-component',['myVar1'=> $something, 'myVar2'=>$somethingElse])
@endcomponent

//my-component.blade.php
@myBladeDirective('Two variables accessible')

//Boot method of relevant service provider
Blade::directive('myBladeDirective', function ($someVar) {
    return "<?php echo $someVar : {$myVar1} and {$myVar2};?>
});
助手定义:

Blade::directive("do", function ($expr) {
    return "<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter($expr); ?>
});
if(!function_exists('highlight')){

    function highlight($expression, $string){
        $expressionValues = preg_split('/\s+/', $expression);

        foreach ($expressionValues as $value) {
            $string = str_replace($value, "<b>".$value."</b>", $string);
        }

        return $string;
    }
}
Blade::directive('highlight', function ($passedDirectiveString){
        return "<?php echo highlight($passedDirectiveString);?>";
    });
<div>
    @highlight('ho', 'house')
</div>
如果(!function_存在('highlight')){
函数高亮显示($expression,$string){
$expressionValues=preg_split('/\s+/',$expression);
foreach($expressionValues作为$value){
$string=str_replace($value,“$value.”,$string);
}
返回$string;
}
}
刀片指令:

Blade::directive("do", function ($expr) {
    return "<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter($expr); ?>
});
if(!function_exists('highlight')){

    function highlight($expression, $string){
        $expressionValues = preg_split('/\s+/', $expression);

        foreach ($expressionValues as $value) {
            $string = str_replace($value, "<b>".$value."</b>", $string);
        }

        return $string;
    }
}
Blade::directive('highlight', function ($passedDirectiveString){
        return "<?php echo highlight($passedDirectiveString);?>";
    });
<div>
    @highlight('ho', 'house')
</div>
Blade::指令('highlight',函数($passeddirectiveestring){
返回“”;
});
用法(示例):

Blade::directive("do", function ($expr) {
    return "<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter($expr); ?>
});
if(!function_exists('highlight')){

    function highlight($expression, $string){
        $expressionValues = preg_split('/\s+/', $expression);

        foreach ($expressionValues as $value) {
            $string = str_replace($value, "<b>".$value."</b>", $string);
        }

        return $string;
    }
}
Blade::directive('highlight', function ($passedDirectiveString){
        return "<?php echo highlight($passedDirectiveString);?>";
    });
<div>
    @highlight('ho', 'house')
</div>

@突出显示(‘ho’、‘house’)
理解:

Blade::directive("do", function ($expr) {
    return "<?php someFunctionFromMyGlobalOrViewScopThatTakeArrayAsParameter($expr); ?>
});
if(!function_exists('highlight')){

    function highlight($expression, $string){
        $expressionValues = preg_split('/\s+/', $expression);

        foreach ($expressionValues as $value) {
            $string = str_replace($value, "<b>".$value."</b>", $string);
        }

        return $string;
    }
}
Blade::directive('highlight', function ($passedDirectiveString){
        return "<?php echo highlight($passedDirectiveString);?>";
    });
<div>
    @highlight('ho', 'house')
</div>
这相当于写下:

<div>
    {! highlight('ho', 'house') !}
</div>

{!突出显示('ho','house')!}

如果要引用自定义刀片指令中的变量,可能不需要将它们直接传递给该指令。我通过从一个内部调用blade指令解决了这个问题