What is the best way to calculate between attributes of a model, to display in the view?

Asked

Viewed 240 times

0

I’m currently calculating everything in the view, something close to below:

{{{ $object->a + ($object->b==1?5:10) + $object->c * (int)object->d... 

But it doesn’t seem like a good idea. I don’t want to save the calculated value in the database, because I prefer to follow the normal ways.

  • Doesn’t Pq add this behavior to the model? The question example doesn’t give much context ...

  • I’ve never seen them use methods in models (outside scope or relationship), I don’t know if this implies any problem, or somehow violates the MVC standard. I can think of several places where this calculation can be done (model, controller, helper ...), my question is even with regard to good practices. The context is to calculate a final date, based on a duration in periods and the type of period (year, semester or bimonthly), also the number of the initial period (1°,2°)...).

  • This code must be in the class that makes sense (cohesion) this calculation is done in products, users who is the 'owner'? which objects participate in it?

  • It comes from a relationship between two objects. It’s okay to define which model makes the most sense for a method to pick up this value. The question is more whether there should be such methods in a model, because as I said, I have never seen an example, or another programmer who uses this framework do something like this. But anyway, I think I’ll stick with this solution. It seems to me better than calculating in the view. vlw :D

  • 1

    It depends a little on how you structure the project. In some of these logic methods stay in the model and others this code is in a class of BO(business Object) that only works with this, this structure is known as anemic model. The advantage of playing this code either in the model or in the BO is that it is available for use elsewhere, if you leave the code in the view, and need to use elsewhere will have to replicate it(copy&paste) or encapsulate it.

1 answer

0

Create methods with the return of the calculation in the model and pass the method to view through the controller.

Example:

No Model:

public static function calculo(Object $object) : float
{
    return $object->a + ($object->b == 1  ? 5: 10) + $object->c;
}

No Controller:

public function index()
{
    return view('caminho.nome.da.view', ['calculo' => NomeDoModel::calculo()] );
}

Na View:

{{ $calculation }}

Remember:

Model only he knows business rule implementations, validation, verification and etc..

View only knows the data input and output.

Controller co-ordinates the Model and the View invoking methods, unknowingly its implementations.

Browser other questions tagged

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