deansatch's avatar

where to put reusable code?

An example...I am using intervention for image resizing and throughout my app I will be uploading images and resizing them. I have a bit of code between upload and resize where it generates filenames, adds numbers to duplicate filenames etc... I expect to reuse this exactly as it is for all or most image uploads in different models/controllers.

My initial thought was to create a function in a helpers.php file. I had a go, added the helpers.php file to my composer.json..ran 'dump autoload' but can't call the function as it seems to completely ignore the path I set in composer.json.

My questions are: a) is this the best approach? b) if it is, how can I get it to work??

0 likes
1 reply
MikeHopley's avatar
Level 17

Make sure your helpers.php is added to the files array in composer.json. See this Stackoverflow answer.

For most things, I would recommend creating a class instead.

I have a global-functions.php file, like your helpers.php. But I don't put much into it. It's for functions that I want available globally, especially in views. It's mainly for extremely generic stuff, like str_replace_once() (a version of str_replace() that only replaces the first instance).

Even then, there are arguments for wrapping these sorts of functions in a class. Maybe it would be cleaner for me to have an App\Utilities\String class, and then call String::replaceOnce(). The main benefit to the global functions is that they can be used from any view, without passing an instance of the class to the view as a variable.

In your case, you have a service that handles a specific task. This is better as a class, rather than thrown together with a bunch of unrelated global functions. The location and name of the class is totally up to you. You could call it something like App\Services\ImageManager.

Please or to participate in this conversation.