I would like to know what's the best approach to create a helper class for my Artisan commands. I want the helper class to contain some static/non-static function to reduce code duplication as well as the size of my commands and to improve code maintainability. I have App/Library folder in which I prefer to place my helper class.
Asked
Active
Viewed 1,646 times
1
-
1I checked that post and went through all the answers but non of them mention anything about artisan commands, I wanted to know if there are any best practices and/or best approaches to do this for artisan commands. – Bahman.A Oct 29 '18 at 19:15
2 Answers
1
Laravel includes a variety of global "helper" PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient. Laravel documentation on Helper functions
There are lots of resources online to help you with this, I recommend this.

Elisha Senoo
- 3,489
- 2
- 22
- 29
-
1Thank you @Elisha, I'm using the word "Helper" literally. I am aware of laravel helper functions and I use them to some good extend. however my question is about the best approach to create my own helper class which I can write custom functions and use them in my artisan commands – Bahman.A Oct 29 '18 at 18:42
1
Create a helpers.php file in your app/Library
folder (or any location of your choice) and add the following to it:
"autoload": {
"classmap": [
...
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Library/helpers.php" // <---- ADD THIS
]
},
After, run the following command on your command line:
composer dump-autoload
You can now add functions by defining them on the helpers.php

Elisha Senoo
- 3,489
- 2
- 22
- 29
-
1would you please let me know what's the difference of this approach versus creating the helper.php in App/Library and then just importing it to a class with "use" keyword. also does your approach still require the "use". and why either of them would be better than the other one in terms of performance, security, best practices? – Bahman.A Oct 29 '18 at 19:38
-
1
-
1so if I don't want it to be globally available and would like to import it whenever I want to use it would my approach be fine? are there any downsides to not autoloading the class in composer? – Bahman.A Oct 29 '18 at 19:41
-
1The essence of the helpers is to have utility functions that are globally available. If you don't want them to be global, then you can create a model, just as usual, and add the methods to the model. Then you can import them as and when. – Elisha Senoo Oct 29 '18 at 19:45