• 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is a beforeFind on a Model a bad idea?

#3
I think I sort of have worked around this. I created a new BaseModel containing the logic for certain things:


PHP Code:
<?php


namespace App\Models;


use 
App\Classes\JsonStoreResponse;
use 
Config\Services;

class 
BaseModel extends \CodeIgniter\Model
{

    protected $useTimestamps true;
    protected $useSoftDeletes false;

    /**
    * Handle pagination with Ext.data.virtual.Store
    * 
    * @return JsonStoreResponse
    */
    public function getVirtualStoreData()
    {
        $request Services::request();

        $start $request->getGetPost('start');
        $limit $request->getGetPost('limit');

        $builder $this->builder();
        $builder->limit($limit$start);

        $sql str_replace('SELECT''SELECT SQL_CALC_FOUND_ROWS'$builder->getCompiledSelect());
        echo $sql;
        $query $this->db->query($sql);
        $row $query->getResult($this->tempReturnType);
        $query->freeResult();

        $query $this->db->query('SELECT FOUND_ROWS() AS `total`');
        $res $query->getRowObject();

        $result = new JsonStoreResponse(true$res->total);
        $result->setData($row);

        return $result;
    }

    /**
    * Check the item_version of the new data and make sure the data is in sync between
    * front- and back-end before updating.
    *
    * @param $id
    * @param $new_data
    *
    * @return bool
    * @throws \ReflectionException
    */
    public function validateVersionAndUpdate($id$new_data)
    {
        $record $this->find($id);

        // Ext JS increments the item_version by one when saving.
        // item_version - 1 must match what we have in database, otherwise another edit
        // has been made and we bail out.
        if ((int)$new_data->item_version !== (int)$record->item_version) {
            return false;
        }

        $this->update($id$new_data);
        return true;
    }



All my models then extend from this BaseModel and get access to common functions without using events.
Working so far...
Reply


Messages In This Thread
Is a beforeFind on a Model a bad idea? - by tgix - 06-29-2020, 10:29 PM
RE: Is a beforeFind on a Model a bad idea? - by tgix - 06-30-2020, 05:35 AM

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.