1
votes

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
In your Languages.php at the top place namespace App\Helpers; and at the top of your controller use App\Helpers\Languages;. You'll need to composer dumpautoload once.user2094178

1 Answers

0
votes

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:

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

Or specify the FQN when using it:

\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. (route(), 'trans()', etc)