It's not about the pattern. It's about the responsibilities. Does a save()
always mean save current
and save history
. Because if does, the first way is better, but the background is important. You should have two model methods for save and savehistory and what logic repository that groups them.
The second variant is wrong not because of pattern way, but because of lack of checks.
I don't know what does save
and saveHistory
should mean exactly, but let's say you have users
table where you store user information including the last login. And user_login_history
where you save each login.
In this case save()
will try to insert the current timestamp for users lastlogin. But what if it fails? In some circumstances the save()
method return false. A momental lack of db connection, timeout, wrong datatypes, etc. But the method returns non-true value. The execution of UserServices::save()
will continue after exiting from Repository::save()
, and then will go to saveHistory()
and will add login_history for this user with the current timestamp, even your user was not able to login. So you will have false data.
If you want to use the second way, do the proper checks. The simpliest way is:
public function save($id, $data)
{
if(UserRepository::save($id, $data)) { // Updates user
UserRepository::saveHistory($id, $data); // Updates user history
... // etc related method based on successful save()
}
}
Ensure for the right execution of the methods, but stick to the single responsibility.