Welcome Guest, Not a member yet? Register   Sign In
Models as Entities using PHP Traits
#1

(This post was last modified: 08-01-2016, 09:31 AM by prezire.)

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.
Long live CodeIgniter!
Reply
#2

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB