简体   繁体   English

自动加载帮助器文件夹Laravel 5

[英]Autoload Helper folder Laravel 5

I would like to call statics methods in a helpers folders. 我想在助手文件夹中调用静态方法。

I have tried many tutos but it's always for just one file. 我尝试了许多tutos,但始终只使用一个文件。

My config /app/Helpers/Languages.php -> my static class 我的配置/app/Helpers/Languages.php->我的静态类

composer.json composer.json

"autoload": {
    "classmap": [
        "database",
        "app/Helpers/" <- I understand, L5 add in own autoload

app.php app.php

'aliases' => [ ...., 'Languages'      => 'App\Helpers\Languages',

What I tried : 我试过了

  • Add autoload classmap, HelpersServiceProviders class, namespace (work just in blade template, not in a Controller) 添加自动加载类映射,HelpersServiceProviders类,名称空间(仅在刀片模板中工作,而不在Controller中工作)
  • Add autoload psr-4 with and without classmap, namespace 添加带有和不带有classmap,名称空间的自动加载psr-4

For all the method, I need to put the use 'app/Helpers/Languages' but I would like call just Languages::myFunction() without 'use' . 对于所有方法,我都需要使用'app / Helpers / Languages',但是我只想调用Languages :: myFunction()而不使用'use'。 Is it possible ? 可能吗 ?

I already the 'app/' folder in psr-4 so it will be load folder and my file, isn't it ? 我已经在psr-4中找到了“ app /”文件夹,因此它将成为加载文件夹和我的文件,不是吗?

If it's can help when in load a page without I've : 如果在没有我的情况下加载页面时可以帮助您:

FatalErrorException Class 'App\\Http\\Controllers\\Languages' not found 找不到FatalErrorException类'App \\ Http \\ Controllers \\ Languages'

When I updated composer.json, I did't forgot composer dump-autoload 当我更新composer.json时,我没有忘记composer dump-autoload

I don't think the problem you have is because the class is not being autoloaded, but rather because you try to use it the wrong way. 我不认为您遇到的问题是因为该类没有被自动加载,而是因为您尝试以错误的方式使用它。 Even with the alias you added, when using the class from within a namespace (like App\\Http\\Controllers ) you have to either add an import statement: 即使使用添加的别名,在命名空间 (如App\\Http\\Controllers )中使用类时,也必须添加import语句:

use App\Helpers\Languages;
// or with the alias
use Languages;

Or specify the FQN when using it: 或在使用时指定FQN:

\App\Helpers\Languages::myFunction();
// or with the alias
\Languages::myFunction();

You can't really avoid this. 您无法真正避免这种情况。 What you could do, so you don't have to worry about namespaces: use helper functions without a class. 您可以做什么,所以不必担心名称空间:使用没有类的辅助函数。 Just like Laravel's helper functions. 就像Laravel的助手功能一样。 ( route() , 'trans()', etc) route() ,'trans()'等)

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

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