The MVC pattern is strictly related to the interaction of the user with the application, in the most common case through a browser via HTTP requests. That said, your application does not usually live entirely within the MVC component.
Protip: If you're calling a controller from a model, you're doing something very wrong.
In this case, you might use a method inside the User class (or UserProfile class if they are separated) to calculate the profile completion.
For example:
class User extends Eloquent
{
public function calculateCompletion()
{
$completed = 0;
$profileElements = ['first_name', 'last_name', 'email', 'bio' ... ];
$total = count($profileElements);
foreach($profileElements as $element) {
$completed += empty($this->{$element}) ? 1 : 0;
}
return $completed / $total; // 0.8 for 8/10 elements completed
}
}
You don't want to have a static method on a controller doing calculations that are completely related to the model - that introduces single responsibility violations and isn't very intuitive. If you find yourself doing a lot of these calculations, you might even create a UserStatisticsCalculator class that knows how to evaluate the user for % profile completion, posts per day, etc.
Thanks! Can I set the completion parameter inside the function? Because for me it's handy to do a call like this:
$user->calculateCompletion()->save();
lovePizza said:
Anyone can tell me if the my solution is right?
Hi lovePizza,
I think you can use
$user->calculateCompletion()->save();
if you are returning the user himself. Maybe something like:
class User extends Eloquent
{
public function calculateCompletion()
{
$completed = 0;
$profileElements = ['first_name', 'last_name', 'email', 'bio' ... ];
$total = count($profileElements);
foreach($profileElements as $element) {
$completed += empty($this->{$element}) ? 1 : 0;
}
$this->completed = $completed / $total; // 0.8 for 8/10 elements completed
return $this;
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community