0

I created an Artisan command file which handles strings in different encodings.

I needed to implement a mb_str_pad function (and found this one).

I created a helper file app/Library/Helpers/StringHelper.php:

<?php

if (!function_exists('mb_str_pad')) {
    function mb_str_pad() {
        :
        :
    }
}

Then I added it to composer.json file:

"autoload": {
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Library/Helpers/StringHelper.php" // <-- Here
    ]
},

And run composer dump-autoload.

When I try to run the command (php artisan mytasks:generate) I get this error:

Call to undefined function App\Console\Commands\mb_str_pad()

2nd try:
I also tried to add a service with:

php artisan make:provider StringHelperServiceProvider

In the register() function I put:

require_once app_path('Library/Helpers/StringHelper.php');

And in app.php added to providers array:

App\Providers\StringHelperServiceProvider::class,

But I get the same error.

=========================== Edit ======================

I have no good explanation for it, but now the same code works fine.

The only thing I did was to test my function with Tinker:

$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> mb_str_pad("Hello", 10);
=> "Hello     "
>>> mb_str_pad("Hello", 10, ' ', STR_PAD_LEFT);
=> "     Hello"
>>> mb_str_pad("Helló", 10, ' ', STR_PAD_LEFT);
=> "     Helló"
>>> 

I leave this question in case it will help somebody.

guyaloni
  • 4,972
  • 5
  • 52
  • 92

2 Answers2

1

After creating the helper file you need to add the pathe of it to composer.json in files section under autoload. Then you should be able to use your helper function like any other framework helper functions.

"autoload": {
    "files": [
        "app/helper.php"
    ],
},

After updating composer.json run composer dumpautoload.

Be sure to check whether function already exist before declaring

if (!function_exists('mb_str_pad')) {
    // Your code
}
chanafdo
  • 5,016
  • 3
  • 29
  • 46
1

Instead of defining the helper file in your composer.json, you can also require it in your App\Providers\AppServiceProvider::register() method:

$filenames = glob(app_path('Library/Helpers/*.php'));
if ($filenames !== false && is_iterable($filenames)) {
    foreach ($filenames as $filename) {
       require_once $filename;
    }
}
Namoshek
  • 6,394
  • 2
  • 19
  • 31