简体   繁体   中英

making a helper like laravel defaullt request helper

i want to make a helper function that i use it widely in my project almost any where or some other helper functions that maybe used now as an example i have laravel request helper in mind like below :

request()->get('name);

now i know that any where in blade or controller or elsewhere if i use it it works . now i have 2 questions . 1-how to make a helper like this that does something and can be used easily and widely 2-is that wise to make some helper like that ???

Create a helper class in app\\Helpers\\GlobalHelper.php

<?php


namespace App\Helpers;


class GlobalHelper
{
    public static function helloWorld()
    {
        return "Hello World"
    }
}

Then in your config\\app.php in the aliases array add

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

Then in a blade file you can use {{ Helper::helloWorld() }} or in a controller you can use \\Helper::helloWorld();

To make global helpers, you can do it like so.

Add a php file (not class) to the following the following path app/Helpers/helper.php .

if (! function_exists('helper')) {
    function helper() {
        return new Helper();
    }
}

To make it similar to Laravels , the approach is to make an object you can call methods on the initial helper call will return.

class Helper {
    public function getHelp() {
        return 'did this help?';
    }
}

Now get composer to autoload your file with the helper function.

"autoload": {
    "files": [
        "app/Helpers/helper.php"
    ]
}

This will enable you to call the following.

helper()->getHelp(); // returns: did this help?

For your last question.

Is is wise to make some helper like that?

In object oriented design this is an anti pattern as it deals with global functions and should be either static namespaced calls or objects. However in the context of Laravel i really enjoy what you can do with these helpers and right now, in my current project, we have global functions dealing with formatting floats to our locale money string representation that have helped a lot and is very pleasant to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM