Where should a globally used method be?

2

I have a method called parser, in short its code is:

public function parser($local) {

    $file = storage_path($local);
    $csv = Reader::createFromPath($file);
    // remove cabeçalho (ignora a primeira linha
    // $novo = $reader->setOffset(0)->fetchAll();
    // retorna o cabeçalho
    // $headers = $csv->fetchOne();

    foreach ($csv as $row) {
        $novo[] = ["nome" => $row[0], "idade" => $row[1], "outro" => $row[2]];
    }

    \DB::table('teste')->insert($novo);
}

The above method will be used in several different controllers, so my doubts are:

  • Because this is a method that may be present in many controllers, where should I put this code?
  • In what part of the Laravel framework should I allocate the file that will have this code?
  • Any example or practical demonstration?
asked by anonymous 06.03.2017 / 14:55

2 answers

2
  

In what part of the Laravel framework should I allocate the file that will have this code?

You can create your own file to load your own functions.

Create a file resources/funcoes.php

Change your composer.json :

"autoload": {
    // ...
    "files": [
        "resources/helpers.php"
    ]
}

Run the command composer dump .

Now all the functions you add in resources/funcoes.php will be globally available.

    
06.03.2017 / 15:07
-2

You can also put this method in a controller of your choice and in the controllers where you want to use the method you can do it as follows:

app('App\Http\Controllers\NomeController')->parser();
    
11.03.2017 / 16:08