简体   繁体   English

为什么 Laravel 找不到我的 function 但 IDE 可以?

[英]Why can't Laravel find my function but the IDE can?

I have a helpers.php file in the app directory of my Laravel project.我的 Laravel 项目的app目录中有一个helpers.php文件。 In this file, I have a function that checks if an item's image is in the storage file and if it isn't it replaces it with an image not found, here is the file:在这个文件中,我有一个 function 来检查项目的图像是否在存储文件中,如果不是,它将用未找到的图像替换它,这是文件:

function productImage($path)
{
    return ($path != null) && file_exists('storage/' . $path) ? asset('storage/' . $path) : asset('img/error/img-not-found.jpg');
}

This is where it is called in one of my blade.php files:这是在我的一个刀片中调用它的地方blade.php文件:

@foreach($products as $product)
    <div class="product">
        <a href="{{ route('shop.show', $product->slug) }}" class="linkToInfo">
            <img src="{{ productImage($product->image) }}" alt="{{ $product->name }}" class="productImg">
            <p class="productData">{{ $product->name }}</p>
            <p class="productData">{{ $product->presentPrice() }}</p>
        </a>
    </div>
@endforeach

When I try and load this page tho, I get this error:当我尝试加载此页面时,我收到此错误:

在此处输入图像描述

You need to either register (via alias) the class or instantiate it so that blade sees it when compiling.您需要注册(通过别名) class 或实例化它,以便刀片在编译时看到它。

Instantiate within blade :在刀片内实例化

{{ \App\Helpers::instance()->productImage($product->image) }}

Or, what I've done usually is to create an alias for your Helper class in config\app.php .或者,我通常所做的是在config\app.php中为您的助手class创建一个别名 This reduces a little overhead and typing as well.这也减少了一点开销和打字。

Alias:别名:

'aliases' => [
   ....
   'Helpers' => App\Helpers::class
]

Then call the alias in your blade (or whatever) file.然后在刀片(或其他)文件中调用别名。

\Helpers::instance()->productImage($product->image);

I do a lot of static functions in the Helper class so I don't need to instantiate them.我在 Helper class 中做了很多 static 函数,所以我不需要实例化它们。 Eg \Helpers::productImage($product->image) .例如\Helpers::productImage($product->image) But the above works just as well too.但上述方法也同样有效。

Note caps on the class:)注意 class 上的上限:)

HTH高温高压

If you want to use the function "as is" (from the global namespace), you need to add the helpers.php file path to the autoload.files part of your composer.json file, like this:如果要“按原样”使用 function(来自全局命名空间),则需要将 helpers.php 文件路径添加到 composer.Z466DEEC76ECDF5FCA6D38571F6Z 文件的autoload.files部分,例如:

"autoload": {
    "psr-4": {
         ...
     }
     "files": [
         "app/helpers.php"
     ]
}

Then you should execute the dump-autoload command from your terminal to update the autoloader:然后你应该从你的终端执行dump-autoload命令来更新自动加载器:

composer dump-autoload

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

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