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

Asked

Viewed 2,486 times

0

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

In my bank I have a code(string), for example "[paragraph]". I will transform 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 put these functions inside the template? or should I create helpers to use in the views?

Thank you very much and sorry for anything. Hugs

Ps.: I am using Laravel 5.1

1 answer

4


Joseph, in Laravel, create a file helpers.php in your briefcase app and automatically load it by editing the composer.json:

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

Then update the project’s Poser by running 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 by views. See how to call the function getData above within a View (using Blade):

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

  • Hello Felipe, thank you so much for your help. But a question continues, where will I call these functions that are in the helper file? I create accessors and mutators in the database model to change the string or send my string to the view and access these functions in the view itself or access the functions by the controller and send the string to the view already modified? I hope I was clear.

  • @Josébadger, I updated my answer. Now there is no mistake! haha

  • Got it, man, thank you so much.

Browser other questions tagged

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