Where should a globally used method be located?

Asked

Viewed 50 times

2

I have a method called parser, in short your 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 it is a method that may be present in many controllers, where should I put this code?
  • In which part of the structure of Laravel should I allocate the file that will have this code?
  • Some example or practical demonstration?

2 answers

2

In which part of the structure of Laravel 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

Alter your composer.json:

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

Turn the command composer dump.

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

-2

It is also possible to put this method on a controller of your choice and on controllers where you want to use the method you can do it as follows:

app('App\Http\Controllers\NomeController')->parser();

Browser other questions tagged

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