简体   繁体   English

在非类帮助文件中添加 Laravel 依赖项

[英]Adding Laravel dependency in non-class helper files

I recently upgraded Laravel version in the project to 6.x.我最近将项目中的Laravel版本升级到6.x。

Now I know the helpers class have been removed from Laravel 6.0 version.现在我知道helpers class 已从 Laravel 6.0 版本中删除。

But anyway I need to keep the [root-dir]/helpers.php file which is functions oriented, non-class file containing general purpose helper functions.但无论如何,我需要保留 [root-dir]/helpers.php 文件,它是面向函数的、包含通用帮助函数的非类文件。

In that file I need to replace all the custom functions starting with str_ like str_contains with Illumimnate\Support\Str counterparts like Str::contains .在该文件中,我需要将所有以str_开头的自定义函数(如str_containsIllumimnate\Support\Str对应的Str::contains For example:例如:

if(!function_exists('is_bot'))
{
    /**
     * userAgent is the user-agent header
     * from the request object
     * @param $userAgent
     * @return bool
     */
    function is_bot($userAgent)
    {
        return str_contains($userAgent, config('bot_check'));
    }
}

How can I do that?我怎样才能做到这一点?

You can only use namespace and use within class files.您只能在 class 文件中使用namespaceuse You could transform your helpers.php file into a class like this:您可以像这样将您的helpers.php文件转换为 class 文件:

<?php

namespace App;

use Illuminate\Support\Str;

class Helper
{
    public static function is_bot($userAgent)
    {
        return Str::contains($userAgent, config('bot_check'));
    }
}

And call is_bot function inside your Laravel application with \App\Helper::is_bot($userAgent) .并使用\App\Helper::is_bot($userAgent)在 Laravel 应用程序中调用is_bot function 。

The helpers removed due to a guy being complaining about them however they moved it to a new package https://github.com/laravel/helpers由于一个人抱怨他们,帮助者被移除,但他们将其移至新的 package https://github.com/laravel/helpers

Link to laravel's pull request https://github.com/laravel/framework/pull/26898链接到 laravel 的 pull request https://github.com/laravel/framework/pull/26898

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM