Laravel: Adding those missing helpers you always wanted

One of the things I like from any PHP project is having global helpers. You know, those functions you can call anywhere and remove or save you many lines or verbosity into one, maybe two, while allocating in one place any logic.

$expected = from($this)->do('foo');

The problem with Laravel itself is that sometimes is not enough with the helpers it includes. The ones included are mostly quick access to Services (like cache()) or Factories (like response()), and some that help you having an expected result (like data_get).

For example, let’s say we want a function be called multiple times but sleep between executions, like we would need to avoid rate limiting for an external API. Without a helper, we will have to resort to create a Class and put the logic inside a public static method, and hopefully remember where it is located.

class Logics
{
public static function logic_sleep($times, $sleep, $callback)
{
// Run and sleep between calls.
}
}Logics::sleep(4, 10, function() {
// ...
});

Using this technique makes your global not so globally. Since this is one of many thing I need in my projects, I decided to create a package with more global helpers:

Larahelp

Those helpers you always wanted

The main idea of a global helper, at least to me, is to have a piece of code that offers simplicityreadability and flexibility. Think about them as small swiss knives that you may put in your pocket.

For example, the above can become its own global function, and we can call it literally anywhere.

public function handle()
{
logic_sleep(10, 5, function () {
$this->uploadRecords();
});
}

The helper is very simple to operate, but we won’t know what the hell it does behind the scenes unless we dig into the source code, which is fair. In any case, having a global function of one or two words makes the whole code more readable. And since it’s our own helper, we can call it anything we want.

How to add your own helpers

But that’s is only one of the many helpers I decided to create for things I use a lot.

To add global helpers to your project, you can simply add a PHP file with the global functions you want anywhere in your project (preferably inside your PSR-4 root folder) and tell Composer to load it.

You are free to add how many files you want. I decided to separate them into categories like I did for my package to avoid having a wall of text full of functions.

"autoload": {
"psr-4": {
"App\\": "app"
},
"files": [
"app/Helpers/datetime.php",
"app/Helpers/filesystem.php",
"app/Helpers/http.php",
"app/Helpers/objects.php",
"app/Helpers/services.php"
]
},

I’m opened to suggestions too, so give it a go if you think it may be useful for you:

DarkGhostHunter/Larahelp

Supercharge your Laravel projects with more than 35 useful global helpers.

github.com

Comments are closed.