Autoload Helper folder Laravel 5

时间:2015-07-08 16:02:49

标签: php laravel composer-php autoload psr-4

I would like to call statics methods in a helpers folders.

I have tried many tutos but it's always for just one file.

My config /app/Helpers/Languages.php -> my static class

composer.json

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

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)
  • Add autoload psr-4 with and without classmap, namespace

For all the method, I need to put the use 'app/Helpers/Languages' but I would like call just Languages::myFunction() without 'use' . Is it possible ?

I already the 'app/' folder in psr-4 so it will be load folder and my file, isn't it ?

If it's can help when in load a page without I've :

FatalErrorException Class 'App\Http\Controllers\Languages' not found

When I updated composer.json, I did't forgot composer dump-autoload

1 个答案:

答案 0 :(得分:0)

我不认为你遇到的问题是因为这个类没有被自动加载,而是因为你试图以错误的方式使用它。即使使用了您添加的别名,在命名空间中使用中的类(如App\Http\Controllers)时,您也必须添加一个import语句:

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

或者在使用时指定FQN:

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

你无法避免这种情况。你可以做什么,所以你不必担心命名空间:使用没有类的辅助函数。就像Laravel的助手功能一样。 (route(),'trans()'等)