2

i found out there are several ways to access a model attribute:

// In Model Class 1.
public function getUsername()
{
    return $this->username;
}

// OR 2.
public function getUsername()
{
    return $this->attributes['username'];
}

and then calling methods,

or just simply call the attribute when needed:

// 3.
$user->username;

What is the difference between these 3 methods? and which to use? best practice, performance and OOP?

2 Answers 2

3

The first two are correct from the point of view of OOP, because for those who use the object it should not matter how the object does to return the value to you. In the end, this Laravel mechanism points to the same variable and the implementation is almost the same.

But the third one is wrong since it accesses the attribute directly, because if you need to change the value format in the future, it would be much simpler to deal with this when returning the method.

Sign up to request clarification or add additional context in comments.

Comments

1

In Laravel option 1 and 2 are redundant and leads to lot of excess boiler plate, option 3 accessing the attribute directly uses the Laravel Eloquent Model accessor pattern to basically do what option 2 is doing. Whereas option 1 is just a getter to call option 3 anyway.

From the point of a view of a pure OOP approach, option 3 is questionable, but if you're using Laravel, it is the recommended method otherwise you're just fighting the framework's intended ease of use features.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.