Where to treat data in an MVC project

0

I'm using Laravel as an example. In Controller I do 2 searches.

public function index()
{
    $page_title = "Relatório";
    $projetos = Projetos::orderBy('alguma_coluna')->get();
    $subprojetos = Subprojetos::get();
    return view('pages.relatorio.index',
        compact('page_title','projetos ','subprojetos ')
    );
}

I need to do a treatment before printing this data in View .

The code below is just an example of data processing

foreach($projetos AS $thisRow) {
    $isDuplicate = false;
    $projeto_nome =  $thisRow["projeto_nome"];
    $hasNewIcon = $thisRow["hasNewIcon"];
    $img_src = $thisRow["img_src"];

    if($hasNewIcon === "1"){
        $hasNewIcon = "<img src='algumaimg.jpg'>";
    } else {
        $hasNewIcon = "";
    }
    foreach ($subprojetos AS $r) {
        $subprojeto_nome = $r["subprojeto_nome"];
        if($contador > 0){
             $isDuplicate = true;
        }
        $contador++;
    }
    $html .= <<<HTML
                     <div class="col-lg-2 col-md-2 col-xs-6 thumb">
                            <img src="{$img_src}" class="img-responsive"/>
                            <div class="equal-height-panels">
                                <div class="row">
                                  <h5 class="text-center">{$projeto_nome}</h5>
                                    {$hasNewIcon}
                                </div>
                            </div>
                    </div>
HTML;
}

My question is: Should I do this treatment where? No Controller , View or Model ?

    
asked by anonymous 22.09.2016 / 19:14

2 answers

2

You can use a class responsible for representing your templates for any type of output, this includes html, json, and xml. There is a design framework pattern commonly used in Ruby called MVP (Model-View-Presenter) .

Fortunately there is already a library in Github that does it for you, and it has been specially developed for Laravel by Jeffrey Way, I do not know if you know but who writes and writes the Laracasts classes .

This library allows you to create classes that are responsible for representing your model for the view. Your code looks something like this:

Presenter

<?php
namespace App\Presenters;

use Laracasts\Presenter\Presenter;

class UserPresenter extends Presenter {

    public function fullName()
    {
        return $this->first . ' ' . $this->last;
    }
}

Template

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;

class User extends Model {

    use PresentableTrait;

    protected $presenter = 'UserPresenter';
}

View

<h1>Olá, {{ $user->present()->fullName }}</h1>

This brings many improvements to your code, especially when you need to change the presentation logic of your template.

  • Remove duplicate code.
  • Decrease code lines within your HTML, at most one call to a function.
  • If you need to modify the way that this data is sent to your view, simply modify the method within the presenter class that the whole system accompanies this change.
  • You can apply tests in your class responsible for presenting your model, avoiding code breaking.

An extra tip, if one day you come across a lot of code responsible for building queries inside your controller, you can escape to Repository Pattern .

    
23.09.2016 / 21:20
0

This factor of where to treat is very interesting, but HTML is in View , the other code needs to be refactored, improved, objective, and clear.

Example:

foreach($projetos AS $thisRow) 
{
    $isDuplicate = false;

    $projeto_nome =  $thisRow["projeto_nome"];

    $hasNewIcon = $thisRow["hasNewIcon"];

    $img_src = $thisRow["img_src"]; 

    $hasNewIcon = ( isset($hasNewIcon) && $hasNewIcon === "1" )
                  ? "<img src='algumaimg.jpg'>" 
                  : "";    

    foreach ($subprojetos AS $r) 
    {
        $subprojeto_nome = $r["subprojeto_nome"];
        $isDuplicate = $contador > 0;
        $contador++;
    }

    //HTML é na View, então não é aqui !!!
}

So that lot of code turned that up, and improved, but, I do not know what is the reason that led you to make this code, in that code snippet the $isDuplicate variable has no purpose whatsoever, maybe is simpler and one thing when working with Framework MVC it already has a separation of responsibility and that:

Inthisimageitisclear,theseparationofresponsibility,wherecontrollerinteractswithModeltopassdatatoView,andcontroller,canyes,treatinformation,decisionsandstructurewithoutanyproblem,whatIworryaboutisthecodingexaggerations,andmixresponsibilitiesasIhadinyourquestioncode,thatyesisverywrong.Inyourcode,prepareallrelatedinformationfromthisViewandpassthemthroughtheFramework'sowncommands.

Youalsohave design patterns , which is a great help for writing object-oriented code, It's good to study!

    
23.09.2016 / 02:02