How to create functions available globally in the Standard?

Asked

Viewed 2,086 times

3

I would like to create functions that are globally available to reuse the code.

What would be the best way to do this, in the Standard...

The flow I need would be like this.:

I’ll get a requisition " Route "

then I will process > "Controler " in this case I will have to do several processing so I thought to do various functions that can be used, in which case I will use third party API for processing as well. then I will display using > "View Blade".

Any idea would be welcome...

  • I don’t know if Laravel has something for that already, but I suggest putting these functions separately in a file and using a namespace in that file, then you can use something like MyUtils\myFunction()

1 answer

5


What you’re probably looking for is a Helper class, a Helper class.

1 - Create a file in the /App/Helpers/Helper.php path

<?php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

2 - Add a nickname, Alias, to the config/app.php file

<?php

'aliases' => [
 ...
    'Helper' => App\Helpers\Helper::class,
 ...

3 - Use in views

{!! Helper::shout('exemplo de uso de helper!!') !!}

4 - Use in any controller or other places:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

    class SomeController extends Controller
    {

        public function __construct()
        {
            Helper::shout('now i\'m using my helper class in a controller!!');
        }
        ...

Source in English

Browser other questions tagged

You are not signed in. Login or sign up in order to post.