Reputation: 106
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?
Upvotes: 2
Views: 1294
Reputation: 1265
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.
Upvotes: 1
Reputation: 131
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.
Upvotes: 3