laravel 5 6 7 Creating Your Own PHP Helper Functions

Creating Helpers file

You could place your helper file anywhere in your Laravel application, it is standard to put it under your app directory.

Let’s create a Helpers directory under app and create a Helper.php file. These are the following contents of the file.

if (!function_exists('human_file_size')) {

    /**

     * Returns a human readable file size

     *

     * @param integer $bytes

     * Bytes contains the size of the bytes to convert

     *

     * @param integer $decimals

     * Number of decimal places to be returned

     *

     * @return string a string in human readable format

     *

     * */

    function human_file_size($bytes, $decimals = 2)

    {

        $sz = 'BKMGTPE';

        $factor = (int)floor((strlen($bytes) - 1) / 3);

        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $sz[$factor];

 

    }

}

 

if (!function_exists('in_arrayi')) {

 

    /**

     * Checks if a value exists in an array in a case-insensitive manner

     *

     * @param mixed $needle

     * The searched value

     *

     * @param $haystack

     * The array

     *

     * @param bool $strict [optional]

     * If set to true type of needle will also be matched

     *

     * @return bool true if needle is found in the array,

     * false otherwise

     */

    function in_arrayi($needle, $haystack, $strict = false)

    {

        return in_array(strtolower($needle), array_map('strtolower', $haystack), $strict);

    }

}

If you are using a class and its methods are your helpers you can start the file with namespace declaration.

namespace App\Helpers;

If you do not use the namespace declaration, these functions will become globally available and you can use them without even specifying the namespace. All the Laravel built-in helper functions are defined without a namespace. Also, helper class will also be available globally. Therefore, if you want to use helpers without specifying namespace simply remove this line.

There are a few caveats when defining these functions. All the Laravel helper files functions are rapped in a check to avoid function definition collisions.

if (!function_exists('human_file_size')) {
    function human_file_size($bytes, $decimals = 2)
    {
        // ...
    }
}

If you skip this check, collisions will occur any time you redefine a function with the same definition. You could either use this check or you could also prefix your function names to avoid collisions.

Now, that’s it as far as our helper file is concerned. Let’s see how you can use helper file in Laravel application.

  • You can either autoload helper file with composer. Then, you could use these functions anywhere in your application.
  • You could also use the Laravel service provider to register this file. Laravel will load it along with other dependencies.
  • You can also use a package that gives you all of this functionality.

Let’s see how we can use all of these methods.

Using Composer to Autoload Files

First one is pretty easy and straightforward. Simply go to composer.json file located in your Laravel project and you will see autoload key. Composer has a files key (an array of file paths that you want to autoload) that you can use in your autoload key. It will look like this:

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

After changing composer.json file and adding a new path to the files array, you need to dump the autoloader. Simply run this command from the terminal in your Laravel project directory.

composer dump-autoload

Now your helper file will be automatically loaded in your Laravel project.

Using service providers to load file

Let’s see how you can use service providers to autoload Helper file. Go to the command line in the root of your application and run the following command to create a new service provider.

    php artisan make:provider HelperServiceProvider

You will see this message logged onto your console screen

    Provider created successfully.

Once the service provider is created successfully, open that file. In the register method require your Helper files.

public function register()
{
    $file = app_path('Helpers/Helper.php');
    if (file_exists($file)) {
        require_once($file);
    }
}

In the register method, we include our dependencies. In a large-scale project, it is possible that you have multiple helper files in a directory and you want to require all of them. You could change the register method like given below and your service provider will load all of the files in the Helpers directory.

public function register()
{
    foreach (glob(app_path() . '/Helpers/*.php') as $file) {
        require_once($file);
    }
}

It will require all of the files present in the app/Helpers directory.
Now that our service provider is completed, we need to register our service provider, so, that Laravel will load it during bootstrapping. For this, go to config/app.php and add the following line in the providers array at the end.

    App\Providers\HelperServiceProvider::class,

If your helper file involves a class that has those helper methods and you have specified namespace, you could use them with little effort by defining an alias. You can do that easily by adding the following at the end of the aliases array in config/app.php file.

    'Helper' => App\Helpers\Helper::class,

By adding this in the alias array, you will be able to call your helpers by using the Helper keyword. That’s all for creating your helpers with service providers.


No comments

Note: only a member of this blog may post a comment.