Welcome Guest, Not a member yet? Register   Sign In
Entity Classes and Time
#1

(This post was last modified: 02-03-2025, 02:54 PM by grimpirate.)

I'm confused on how best to proceed. I created a Model with an $allowedFields 'date_request'. I created an Entity class that has 'date_request' as one of its $attributes. My confusion stems from two places in the docs: In using my 'date_request' field should I define it as a 'datetime' type in the $casts array or should I place it into the $dates array to mutate it automatically? Neither? Both?

What are the issues/benefits of  these approaches in terms of the Entity and Time classes?

Why bother with $dates at all if I have the ability to mutate via cast; more peculiarly if I can specify a cast that is nullable?
Reply
#2

using $cast is a more customizable option. And I redefine all get/set for the Entity - this extend the possibilities and gives more control.
PHP Code:
// UserModel.php
    protected array $casts    = [
        'id'              => '?int',
        'phone'          => 'phone',
        'date_birth'      => '?date',
        'blocked'        => '?datetime',
        'updated_at'      => '?datetime',
        'visited_at'      => '?datetime',
        'deleted_at'      => '?datetime',
    ];

// User.php
    public function getDateBirth(): ?Time
    
{
        return $this->dateBirth;
    }

    public function setDateBirth(?Time $dateBirth): self
    
{
        $this->dateBirth $this->attributes['date_birth'] = $dateBirth;

        return $this;
    
Simple CI 4 project for beginners codeigniter-expenses ( topic )
Reply
#3

Seems like this runs the "risk" of casting your updated_at and deleted_at twice as the docs state: "By default, the Entity class will convert fields named created_at, updated_at, or deleted_at into Time instances whenever they are set or retrieved." which seems like an avoidable waste of operations?
Reply
#4

Nothing will break, you need to reset the default dates for Entity.
PHP Code:
    protected $dates = []; 
Simple CI 4 project for beginners codeigniter-expenses ( topic )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB