hi all, i'm working on a project with CI4 recently, i really love CI4, but i discover some problem with the entity class, it's not a big deal if your data is not big, but it will comsume a lot of RAM or CPU for page load if you use it with big data record
The problem was:
i have and Entity class ( Story ), and in this Entity i create a custom attribute to load uploader infor
Code:
public function getAuthorInfo() {
if (empty($this->id)) {
throw new \RuntimeException('Object must be created before getting data.');
}
if ( !empty($this->attributes['author']) && !is_array($this->attributes['author']) ) {
$authorId = json_decode($this->attributes['author']);
if ( is_numeric($authorId) ) {
$info = model(StoryAuthorModel::class)->find($authorId);
if ( !empty($info) ) {
$info->url = base_url('tac-gia/'.$info->short_name);
$this->author_info = $info;
}
}
}
return $this->author_info;
}
In the Story page, i'm loading about 100 stories, and display the uploader info with this line of code
Code:
<?php
if ( isset($row->uploader->id) ) :
?>
<span class="badge badge-info">
<a style='color: white'
href='<?=base_url($config->adminSlug.'/story?post='.$row->uploader->username)?>'>
<?=$row->uploader->username?>
</a>
</span>
<?php endif; ?>
with this code, when i'm looking at the debuger bar, and check the database tab, i saw 3 queries running to find user data, it's mean everytime i use
$row->uploader the Entity run and excute query to find the data, this will be a problem if we use it multiple time or loading big resource, it will make the system loading slow
So, i change my code to
Code:
<?php
$uploader = $row->uploader??null;
if ( isset($uploader->id) ) :
?>
<span class="badge badge-info">
<a style='color: white'
href='<?=base_url($config->adminSlug.'/story?post='.$uploader->username)?>'>
<?=$uploader->username?>
</a>
</span>
<?php endif; ?>
this one, i just loading the database once
i wonder if there is anyway in entity class that can help us keep the datalive without finding it in the database everytime when we use entity object