Welcome Guest, Not a member yet? Register   Sign In
Entity loading problem
#1

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
Reply
#2

ok look at my code  
and a make sure care Entity dirtoary for Entities files 


PHP Code:
<?php

namespace  CoreSite
\Controllers;


use 
CoreSite\Entities\SettingEntity;
use 
CoreSite\Libraries\ParameterDataInput;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CoreSite\Models\SettingModel;

class 
Setting extends ApiController
{


    /**
     * index function
     * @method : GET
     */
    public function index()
    {

        $settingModel = new SettingModel();

        $parameterDataInput = new ParameterDataInput();

        $parameterDataInput->receiveParameters();
        if ($parameterDataInput->getExact()) {

            $result $settingModel->where($parameterDataInput->getExactExplode('key'), $parameterDataInput->getExactExplode('value'))
                ->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))
                ->paginate(10'default'$parameterDataInput->getPage());

        } else if ($parameterDataInput->getExcept()) {

            $result =  $settingModel->where($parameterDataInput->getExceptExplode('key') . ' !='$parameterDataInput->getExceptExplode('value'))
                ->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))
                ->paginate(10'default'$parameterDataInput->getPage());

        } else {

            $result $settingModel->like($parameterDataInput->getFilterExplode('key'), $parameterDataInput->getFilterExplode('value'))
                ->orderBy($parameterDataInput->getSortExplode('key'), $parameterDataInput->getSortExplode('value'))
                ->paginate(10'default'$parameterDataInput->getPage());

        }



        return $this->respond([
            'data' => $result,
            'pager' => $settingModel->pager->getDetails()
        ], ResponseInterface::HTTP_OKlang('Response.api.receive'));


    }

    /**
     * show function
     * @method : GET with params ID
     */
    public function show($id null)
    {

        $settingModel = new SettingModel();


        return $this->respond([

            'data' => $settingModel->where('id'$id)->paginate(1'default'),
            'pager' => $settingModel->pager->getDetails()
        ], ResponseInterface::HTTP_OKlang('Response.api.receive'));

    }

    /**
     * create function
     * @method : POST
     */
    public function create()
    {
        $settingModel = new SettingModel();
        $settingEntity = new SettingEntity();
        if ($this->request->getJSON()) {
            //get request from Vue Js


            $rules = [
                'key' => 'required|min_length[3]|max_length[255]|is_unique[setting.key]',
                'value' => 'required|min_length[3]|max_length[255]',
                'description' => 'required|min_length[3]|max_length[255]',
                'status' => 'required',
            ];

            if (!$this->validate($rules)) {

                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_ACCEPTABLElang('Response.api.validation'));

            }


            $settingEntity->key $this->request->getJSON()->key;
            $settingEntity->value $this->request->getJSON()->value;
            $settingEntity->description $this->request->getJSON()->description;
            $settingEntity->status $this->request->getJSON()->description;
            $settingEntity->createdAt();

            if (!$settingModel->save($settingEntity)) {

                return $this->respond([
                    'error' => $settingModel->errors(),
                    'success' => false,
                ], ResponseInterface::HTTP_BAD_REQUESTlang('Response.api.reject'));

            }

            return $this->respond([
                'data' => ''
            ], ResponseInterface::HTTP_CREATEDlang('Response.api.save'));
        }


    }

    /**
     * update function
     * @method : PUT or PATCH
     */
    public function update($id null)
    {
        $settingModel = new SettingModel();
        $settingEntity = new SettingEntity();
        if ($this->request->getJSON()) {
            //get request from Vue Js

            //get request from Vue Js
            $json $this->request->getJSON();
            if (!isset($id)) {
                $id $json->id;
            }


            $rules = [
                'value' => 'required|min_length[3]|max_length[255]',
                'description' => 'required|min_length[3]|max_length[255]',
                'status' => 'required'
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_ACCEPTABLE,  lang('Response.api.validation') );

            }

            $setting $settingModel->where('id'$id)->first();


            if (is_null($setting)) {


                return $this->respond([
                    'error' => $this->validator->getErrors(),
                    'success' => false
                
], ResponseInterface::HTTP_NOT_FOUNDlang('Response.api.exist'));

            }

            // Success! Save the new password, and cleanup the reset hash.
            // $setting->key = $this->request->getJSON()->key;
            $setting->value $this->request->getJSON()->value;
            $setting->description $this->request->getJSON()->description;
            $setting->status $this->request->getJSON()->status;
            // date_default_timezone_set('Asia/Tehran');
            $setting->updated_at date('Y-m-d H:i:s'time());

            if (!$settingModel->save($setting)) {
                return $this->respond([
                    'error' => $settingModel->errors(),
                    'success' => false,
                ], ResponseInterface::HTTP_BAD_REQUESTlang('Response.api.reject'));

            }

            return $this->respond([
            ], ResponseInterface::HTTP_OKlang('Response.api.update'));
        }


    }

    /**
     * edit function
     * @method : DELETE with params ID
     */
    public function delete($id null)
    {


        $settingModel = new \App\Models\SettingModel();




        $isExist $settingModel->find($id);
        if ($isExist) {

            $settingModel->delete($id);


        }

        return $this->respond([
        ], ResponseInterface::HTTP_OKlang('Response.api.remove'));

    }



PHP Code:
<?php namespace CoreSite\Models;

use 
CoreSite\Entities\SettingEntity;
use 
CodeIgniter\Model;

class  SettingModel extends Model
{


    /**
     * table name
     */
    protected $primaryKey "id";
    protected $table "setting";

    /**
     * allowed Field
     */
    protected $allowedFields = [
        'key',
        'value',
        'description',
        'status',
        'deleted_at',
        'updated_at',
        'created_at'
    ];
    protected $useSoftDeletes false;
    protected $useTimestamps true;
    protected $createdField 'created_at';
    protected $updatedField 'updated_at';
    protected $returnType SettingEntity::class;
    protected $validationRules = [
        'key' => 'required|min_length[3]|max_length[255]|is_unique[setting.key]',
        'value' => 'required|min_length[3]|max_length[255]',
        'description' => 'required|min_length[3]|max_length[255]'
    ];
    protected $validationMessages = [];
    protected $skipValidation false;







PHP Code:
<?php namespace CoreSite\Entities;

use \
CodeIgniter\Entity;
use 
CodeIgniter\I18n\Time;

class  SettingEntity extends Entity
{


    protected $id;
    protected $key;
    protected $value;
    protected $description;
    protected $status;
    protected $created_at;
    protected $updated_at;
    protected $deleted_at;

    //check type of data

//    protected $casts = ['
//    is_flag' => 'boolean'];

    protected $attributes = [
        'id' => null,
        'key' => null,
        'value' => null,
        'description' => null,
        'status' => null,
        'created_at' => null,
        'updated_at' => null,
        'deleted_at' => null,
    ];
    protected $datamap = [
    ];

    protected $dates = ['created_at''updated_at''deleted_at'];

    protected $casts = [
        'status' => 'boolean',
    ];

    protected $permissions = [];

    protected $roles = [];

    public function activate()
    {
        $this->attributes['status'] = 1;
        return $this;

    }

    public function deactivate()
    {
        $this->attributes['status'] = 0;

        return $this;
    }

    public function isActivated(): bool
    
{
        return isset($this->attributes['status']) && $this->attributes['status'] == true;
    }



//    public function __get(string $key)
//    {
//        if (property_exists($this, $key)) {
//            return $this->$key;
//        }
//    }
//
//    public function __set(string $key, $value = null)
//    {
//        if (property_exists($this, $key)) {
//            $this->$key = $value;
//        }
//    }


//    public function setCreatedAt(string $dateString)
//    {
//        $this->attributes['created_at'] = new Time($dateString, 'UTC');
//
//        return $this;
//    }
//
//    public function getCreatedAt(string $format = 'Y-m-d H:i:s')
//    {
//        // Convert to CodeIgniter\I18n\Time object
//        $this->attributes['created_at'] = $this->mutateDate($this->attributes['created_at']);
//
//        $timezone = $this->timezone ?? app_timezone();
//
//        $this->attributes['created_at']->setTimezone($timezone);
//
//        return $this->attributes['created_at']->format($format);
//    }


    public function createdAt()
    {

       // date_default_timezone_set('Asia/Tehran');
        $this->attributes['created_at'] = date('Y-m-d H:i:s'time());
        // $this->attributes['created_at'] = new  Time(date('Y-m-d H:i:s', time()), 'UTC');
        return $this;
    }

    public function updatedAt()
    {

      //  date_default_timezone_set('Asia/Tehran');
        $this->attributes['updated_at'] = date('Y-m-d H:i:s'time());

        return $this;
    }

Enlightenment  Is  Freedom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB