Welcome Guest, Not a member yet? Register   Sign In
Entity cast-on-fill
#1

I was actually surprised that this wasn't already the case... I am curious what everyone thinks about casting entity values during fill(). Consider the following example:
PHP Code:
class Exercise extends \CodeIgniter\Entity
{
    protected 
$dates      = ['created_at''updated_at'];
    protected 
$casts      = ['amount' => 'int'];
    protected 
$attributes = ['name' => 'running'];
}

...

$exercise = new Exercise([
    
'amount' => $this->request->getPost('amount')
]);

(new 
ExerciseModel())->insert($exercise); 

I have defined the "amount" field in my casts to be an integer, but when I fill the new entity with form input it goes in as a string. Not a big deal, if I `var_dump($exercise->amount)` the cast will ensure it comes out as an integer. However, when the model tries to insert it the string version gets sent. Often this isn't an issue, but some databases might not make the conversion leaving you with a string in your database.

So two possible solutions: when fill() is called it runs the values through $cast to ensure they are always of the expected type. The other thought was to add casts to the model's classToArray() method (it already casts time values); this intentionally uses "toRawArray()" instead of "toArray()" to avoid the datamap and magic getters, but I don't see why it should avoid casting types.
Reply


Messages In This Thread
Entity cast-on-fill - by MGatner - 04-14-2020, 10:40 AM
RE: Entity cast-on-fill - by kilishan - 04-14-2020, 10:54 AM
RE: Entity cast-on-fill - by MGatner - 04-14-2020, 11:01 AM
RE: Entity cast-on-fill - by kilishan - 04-14-2020, 11:16 AM



Theme © iAndrew 2016 - Forum software by © MyBB