Welcome Guest, Not a member yet? Register   Sign In
Entity instantiation via find() is wonky
#1
Information 

I have an Entity class where I instantiate an object based on inputs to the constructor. Something like this:
PHP Code:
class MyEntity extends \CodeIgniter\Entity\Entity
{
    protected SomeClass $c;

    public function __construct(?array $data=null)
    {
        $this->= new SomeClass($data['some_param']);
    }


Then I would pull this Entity from the database like this:
PHP Code:
$myEntity model(MyModel::class)->asObject(MyEntity::class)->find($id); 
Whether I use find() or getResult() or probably other retrievers, the constructor is called but $data is null.  After some digging I see that \CodeIgniter\Database\MySQLi\Result::fetchObject instantiates the Entity class with no arguments and calls injectRawData() to load the DB results directly to the Entity::$attributes array.  So the normal getter/setter logic doesn't apply.
Seems like a workaround would be to bust out the constructor logic into its own function, then override injectRawData() and call the function from there as well as the constructor.  Or call some kind of 'init' function to do what the constructor would otherwise do.  Neither option seems super elegant though
I think I understand the reasoning behind this, when you're selecting out potentially thousands of Entity objects, you want to get the data out as fast as possible and skip the overhead of setters, etc.

So my question is, is there any flag or setting that I'm missing that would cause the DB result to be passed to the constructor instead of being loaded via injectRawData()?
Reply
#2

There is no flag or setting like that.

But you will be able to specify constructor in v4.5.0 if you use Model Field Casting (DataConverter).
See https://github.com/codeigniter4/CodeIgniter4/pull/8243
Reply
#3

(03-22-2024, 05:10 PM)kenjis Wrote: There is no flag or setting like that.

But you will be able to specify constructor in v4.5.0 if you use Model Field Casting (DataConverter).
See https://github.com/codeigniter4/CodeIgniter4/pull/8243

Awesome, looking forward to using it. Thanks!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB