CodeIgniter Forums
How to dynamically set properties of the model? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to dynamically set properties of the model? (/showthread.php?tid=77563)



How to dynamically set properties of the model? - blaasvaer - 09-17-2020

I want to set these dynamically upon initialization of the model:

Code:
<?php namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    protected $returnType     = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = ['name', 'email'];

    protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;
}

How can I pass in these values as parameters to the model?

I'd like to do something like this:

Code:
$this->model = new MyModel($config);

But the model obviously expect a ConnectionsInterface and a ValidationInterfave upon construction ...


RE: How to dynamically set properties of the model? - InsiteFX - 09-17-2020

Then Create a BaseModel and pass the parameters through it's constructor.

Your BaseModel should extend the CodeIgniter's Model and all of your Model's
will extend the BaseModel.


RE: How to dynamically set properties of the model? - blaasvaer - 09-17-2020

(09-17-2020, 04:42 AM)InsiteFX Wrote: Then Create a BaseModel and pass the parameters through it's constructor.

Your BaseModel should extend the CodeIgniter's Model and all of your Model's
will extend the BaseModel.

Thanks. Never thought of it that way ... ended up creating a method and pass in the params by calling that after init.