I don't think there is much to simplify with your code.
- Used short array syntax, since you're running PHP 5.5.
- Renamed
$model
to $user
: It increases readability + it's one less character.
- If-statement syntactical sugar brackets removed.
Code:
$row = [
'id' => 123,
'username' => 'Testing',
'status' => 1,
'created_on' => '2014-09-20',
'created_by' => 1,
'updated_on' => null,
'updated_by' => null
];
$user = new User();
$user->id = (int) $row['id'];
$user->username = $row['username'];
$user->status = (int) $row['status'];
$user->created_by = (int) $row['created_by'];
if ($row['created_on']) $user->created_on = new DateTime($row['created_on']);
if ($row['updated_on']) $user->updated_on = new DateTime($row['updated_on']);
if ($row['updated_by']) $user->updated_by = (int) $row['updated_by'];
I have the impression that your User
class is just a container and everybody can edit its properties directly. You might wanna enforce some encapsulation here by using setters and getters. This way you can hide its internal properties and have room to validate any values being set and make sure a User
object can never reach a state it wasn't meant to be in.
About your update:
Am I making the codes more complicated?
Yes! Do you really want to sacrifice all this readability just to get a more "simplified" solution? Really, it ends up over-complicating the solution instead.
Remember that if your code is made out of a bunch of complex and over-complicated logic because you wanted to "simplify" things, only a computer would understand that with no problem. In a week when you come back to look at your code, you will not be able to understand what's happening at a glance. It will take you a minute, and more often then not it makes you forget how the piece of code you're trying to understand fits in the bigger picture.
Martin Fowler said: "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". And that goes especially if you work in a team. You should value readability over simplified code that over-complicates the solution. It will save you (and your team) a lot of time now and in the future.
The reason I made the 2nd version is that I worried the 1st version expands if the $row
expands.
It's completely acceptable that if your user table gets a new usable column that you would also need to add an extra setter in your code for it. Generally it's something that would rarely happen often.
The solution in your post isn't even complete in regards to your concern. For example, what if you decided to update your table with a column modified_on
? You still would have to append || $k == 'modified_on'
to the if-statement expression and add the class property for this new column.