Support the ongoing development of Laravel.io →
posted 10 years ago
Architecture
Last updated 2 years ago.
0

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.

Last updated 10 years ago.
0

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();
0

Anyone can tell me if the my solution is right?

0

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;
    }
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

lovePizza lovepizza Joined 13 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.