CodeIgniter Forums
Models as Entities using PHP Traits - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forum-31.html)
+--- Thread: Models as Entities using PHP Traits (/thread-65854.html)



Models as Entities using PHP Traits - prezire - 08-01-2016

There are a couple of debates in some companies I've worked for about models being entities or not. In CI3, it usually ended something with 2 files: models/User_model.php and models/entities/User.php.

CI3 Example:
PHP Code:
$i $this->input;
$user = new User();
$user->email $i->post('email');
$user->password $i->post('password');
$this->user_model->create($user); 

But for future enhancements of CI4, PHP Traits can be used instead of extending \CodeIgniter\Model.
CI4 Example:
PHP Code:
final class UserModel
{
 private 
$email;
 private 
$pwd;

 use 
BasicCRUD;
 use 
AutoDBConnector;
 use 
InModelValidation;

 
//Email and password getters and setters...


This can be useful for something like:

PHP Code:
final class App
{
 private 
$users;
 public function 
addUser(UserModel $user):bool
 
{
 
//Add user from list.
 //Return bool.
 
}


The reason for this is for the developer to have the flexibility of whether or not his model is a real model, which can connect to a database, or just a plain entity by not using any model Traits at all.


RE: Models as Entities using PHP Traits - kilishan - 08-01-2016

A feature that I didn't know about until about 1 year ago in CI was the ability to have the database results returned as any class that you can set the attributes on. I've become a big fan of the Repository pattern, myself, and that helped make it all work together pretty seamlessly.

That way you have the user_model which handles mainly working with the database to find, save, etc the data. Then entity classes, just like you've mentioned have zero parent classes and are completely standalone.

Oh - and this absolutely made it's way over to CI4.