Laravel and the MVC concept - where do I put my classes / functions?

0

Hello. I am new to Laravel and MVC architecture and have a conceptual doubt.

In my bank I have a code (string), for example "[paragrafo]". I'm going to turn this string into " < p>meu paragrafo< /p> " to be displayed in the view. This transformation will be through some classes or functions that, according to the code returned from the database will generate the respective output string (including html elements).

The question is: where should I place these functions within the model? or should I create helpers to use in views?

Thank you very much and apologize for anything. Hugs

Ps: I'm using Laravel 5.1

    
asked by anonymous 01.07.2015 / 16:20

1 answer

2

José , in Laravel, create a helpers.php file in your app folder and load it automatically by editing composer.json :

"autoload": { 
"classmap": [ ... ],
 "psr-4": { "App\": "app/"
 }, 
"files": [
 "app/helpers.php" // <---- ADICIONE AQUI
] },

Then update the project composer by executing the command:

composer dump-autoload

Example

app/helpers.php

<?php

// ************************
// Criado em 05/02/2015
// Helper com utilidades criado por Felipe D.
// ************************

    /**
     * Retorna data e hora.
     *
     * @param   bool    $hora   Se vai retornar hora também
     * @return  string
     */
    function getData($hora)
    {
        // retorna, mas poderia ser "echo", whatever
        return ($hora ? date("d/m/Y H:i") : date("d/m/Y")) ; 
    }

app/Http/Controllers/DataController.php

<?php

namespace App\Http\Controllers;

use App\Midia;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class DataController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        // Helpers podem ser chamados de QUALQUER lugar, 
        // inclusive pelas views, ex: usando {{ getData(true) }}
        $data = getData(true);

        // ou echo ou die ou carrega view, whatever
        return $data; 

    }
}

As I said in the comment above, Helpers can be called ANY place, including views. Here's how to call the getData function above within a View (using Blade):

<div>Data / Hora: {{ getData(true) }} </div>

    
01.07.2015 / 16:22