Create your own PHP helper function in Laravel

Laravel provides us with many built-in helper functions that you can call anywhere in your application. They allow you to easily work with arrays and objects, paths, strings, URLs and other types of workflows.

Although many helper functions are defined in Laravel core, you can define your own helper functions in Laravel to avoid repeating the same code. It ensures better maintainability of your application.

Let's see how to create your own custom Laravel helper function

Helper functions in Laravel

There are many built-in helpers in Laravel that can be used by your application. They are grouped according to the type of functionality they provide. This is a complete built-in Laravel help file.

arrays and objects

In this group, helpers provide the ability to work with arrays and objects. This group contains helper functions for adding two arrays, collapsing a multidimensional array into a single array, returning the first element of an array, checking for the existence of a given item or items in an array, and performing many other types of operations.

path

This set of helpers returns absolute paths to different directories in a Laravel application, such as app, config, public, resource, storage and the base path of your application.

string

Helpers in this group use string manipulation. You can convert strings to camel case, find the base name of the class, run htmlspecialchars, convert text to kebab case, convert text to case, and perform many other types of string operations.

URL

The helper's group of URLs works with generated URLs. You can generate URLs for controller actions, named route, and fully qualified URLs specifying the path.

Miscellaneous

This class of helpers contains functionality for handling page state, serving containers, authentication, caching, and more.

Create help file in Laravel

In this section, we will go through the creation of a Laravel helper file that can be used globally in a Laravel application. You can organize the location of your helper files, however, I prefer to keep my Laravel project helper files app/Helpers/Helper.phpin . In this tutorial, we will create a help file in my desired location.

Create a help file

You can place your helper file anywhere in your Laravel application, it is standard to place it in your application directory. Let's create a Helpersdirectory and create a Helper.phpfile. These are the following contents of the file.

<?php

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 this file with a namespace declaration.

namespace App\Helpers;

If you do not use namespace declarations, these functions become available globally, and you can even use them without specifying a namespace. All Laravel built-in helper functions are defined without namespaces. Additionally, helper classes will also be available globally. So if you want to use the helper without specifying the namespace, just delete this line.

There are some caveats when defining these functions. All Laravel helper functions are checked to avoid conflicting function definitions.

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

If this check is skipped, there will be a conflict every time a function with the same definition is redefined. You can use this check, or you can prefix it with your function name to avoid conflicts.

Use the help file

Now, as far as our help file is concerned, that's it. Let's see how to use helper files in a Laravel application.

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

Let's see how to use all these methods.

Autoload via Composer

The first one is very simple and straightforward. Just go to the composer.jsonfile and you will see the key loaded automatically. Composer has a key files(an array of file paths you want to autoload) that you can use in an automatic `autoload. Such as:

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

After changing the composer.json file and adding new paths to the files array, the autoload files need to be regenerated. Just run this command from the terminal in your Laravel project directory.

composer dump-autoload

Now your helper files will be automatically loaded into your Laravel project.

Loaded by service provider

Let's see how to use a service provider to automatically load helper files. Go to the command line in the application root directory and run the following command to create a new service provider.

php artisan make:provider HelperServiceProvider

The result of the operation will be displayed

Provider created successfully.

Once the service provider is successfully created, open the file. Add your helper file in the registration method.

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

In the registration method, we include our dependencies. In a large project, you may have multiple helper files in a directory, and you want all of them. You can change the registration method as shown below and your service provider will load all the files in the Helpers directory.

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

It will app/Helpersneed all files in the directory. Now that our service provider is complete, we need to register our service provider, so, Laravel will load it during bootstrap. To do this, go to config/app.phpand providersadd the following line to the array at the end.

App\Providers\HelperServiceProvider::class,

If your helper file refers to a class that has these helper methods, and you've specified the namespace, you can use them effortlessly by defining an alias. You can easily do this by adding the following at the end of the aliases array in the config/app.phpfile .

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

By adding this to the aliases array, you will be able to invoke the helper using the Helper keyword. This is what creates your helper for service providers.

Loading with third-party packages

You can also use a third-party package: Laravel helpers package . You can install it via the composer by running this command in the console from your app's root directory.

composer require browner12/helpers

config/app.phpAdd the following lines to the providersarray in

browner12\helpers\HelperServiceProvider::class,

If you are using Laravel's automatic package discovery feature, you can skip this step. After completing the necessary steps, you can use this command to create a helper file.

php artisan make:helper Helper

It App\Helperswill create a Helper.phpfile in , where you can easily add all the helper functionality.

The specific use of Helper

Now that our functions are defined in the Helper file, with no namespaces defined, we can use them easily. routes/web.phpJust find your routing file in and use this feature for the front page. For example, here is the complete routes/web.phpfile :

<?php

Route::get('/', function () {
    return human_file_size(1024*1024);
});

It will simply return the readable size in bytes passed as parameter. You can call these functions from any controller or view anywhere.

resource

Welcome to leave a message for discussion.

For more PHP related, please go to PHPCasts

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324992637&siteId=291194637