I ran into a weird problem with Codeigniter Database Cache. I'm using it to cache one query result. For this I am enabling it at the begining of the function and disabling right after:
function checkAfter($lastCheck)
{
$this->db->cache_on();
$this->db->where('time >' , date('Y-m-d H:i:s', $lastCheck));
$q = $this->db->get('actions');
$r = $q->result();
$this->db->cache_off();
return (!empty($r)) ? $r : false;
}
I need to delete the cache on the certain event when something is added to database.
It is working fine with $this->db->cache_delete_all(); but when I'm trying to remove one specific method cache like it is explained in user guide it doesn't do anything.
What might be the problem here?
Both methods are called in the same Model. I also tried to enable cache before delete but still nothing.
EDIT
Lets say i have method checkEvents in my main controller which calls the checkAfter method of the model which then works with cache. CI cache engine creates a folder called main+checkEvents under cached forlder where chached data is stored.
so i am trying to remove it with
$this->db->cache_delete('main', 'checkEvents');
call in logEvent method (which saves the new event) of that model.
Related
i am working on yii2 basic and when i update a form, data update in db successfully but update data dnt show in form even after refresh link but when i hard refresh or remove cache then it shows updated data in form , what could be a possible issue ? , because it was working fine few days before but suddenly it starts showing this behavior even an other application is in same server that is working fine , i need help .
is it yii2 configuration issue or server configuration issue?
in db.php i have these two values
'enableSchemaCache' => true,
'enableQueryCache' => false,
i tried enable schema cache to false but no luck.
Seems like there's some sort of (data) caching enabled.
You can :
Check the methods you use to retrieve data from the database to see if caching has been enabled .
Such methods are : find() , findOne() , findAll() .
Check if they have been overridden or extended by your code.
If the default find() method or any of its variants have been extended, then you could also extend the afterSave() method to flush the cache after performing updates to the database.
Here's what I use in my test environment to flush the cache after performing an update .
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
//Clears cache if this is an update
if( !$insert)
{
if(method_exists ($this, 'flushCache'))
{
$this->flushCache();
}
}
}
public function flushCache()
{
Yii::$app->cache->delete($this->getCacheKey());
}
protected function getCacheKey()
{
return self::getCacheKeyPrefix(). $this->getPrimaryKey() ;
}
public static function getCacheKeyPrefix()
{
return self::CACHE_PREFIX . self::getTableSchema()->name;
}
Explanation
After writing to the DB, the afterSave() event is called by Yii.
If an insert was carried out, then cache flushing is skipped. If an UPDATE was performed, then the flushCache method is called to clear the cache.
Note that you should understand how caching has been set up in your own environment and then amend flush the cache as appropriate to suit your needs.
Let me know how it goes.
Thanks and HTH.
What I want to do:
Return a bunch of rows from database, convert in a array stored in memory and make this array visible from the whole project in such a way that other controllers for example can read it. My function is simple as that:
class BoardController extends Controller
{
/*
* returns something like
* ['name' => 'description',
...
]
*
* */
public static function getAll()
{
$boards = Board::orderBy('ordem')->get();
$retorno = array();
foreach($boards as $b)
{
$retorno[$b->sigla] = $b->nome;
}
return $retorno;
}
}
If I just keep calling BoardController::getAll() it will again read from database again. I also tried making this call inside a config file into a variable and returning it there but laravel gave me a 500 error. So, what is the best practice/way to do it?
If you don't want to call the database everytime then the best approach that can be followed here is to use caching and cache the results.
The Approach is simple, You make a Database call once and cache the reaults and the next time you hit the same function you check the cache first whether its empty or not. If its not empty, then return the cached results.
Remember, the cache has a time limit otherwise if you change/update anything in the database then you'll have to clear the cache that is already stored.
Laravel has some features for caching the results. You can see it Here.
Also You can also view this link for more effective implementation of cache in Laravel.
Hope this helps.
I need a help to figure out one issue with the codeigniter caching.
I am running two functions to store a result in cache. This function is in my model :
public function cacheAllCurrencies()
{
$this->db->cache_on();
$this->db->select("name,icon,currency_code");
$this->db->from("currency");
$this->db->where("status='Active'");
$cache_currency_result = $this->db->get()->result();
$this->db->cache_off();
return $cache_currency_result;
}
public function cacheAllCategory()
{
$this->db->cache_on();
$this->db->select("name,url");
$this->db->from("category");
$this->db->where("parent_category='0'");
$this->db->where("status='Active'");
$this->db->order_by('name','ASC');
$cache_category_result = $this->db->get()->result();
$this->db->cache_off();
return $cache_category_result;
}
My these two functions are called in header view like below :
$CI =& get_instance();
$CI->load->model(PUBLIC_DIR.'/commonPage','common');
$currencies = $CI->common->cacheAllCurrencies();
$categories = $CI->common->cacheAllCategory();
Now, when all the page loads, it creates a cache file according to the page opened like home, blog, blog+blogname etc.
Both query generates two cache file in cache folder
1580e4c2413cb09f6ed3bc7fae8cee45 - first function cache result
d7e2452b0424f859e1a5984bd26cbd6c - second function cache result
Now, I have two questions :
I need to delete 1580e4c2413cb09f6ed3bc7fae8cee45 cache file when I update currency table same for the category.
How this file name generated ? I mean how codeigniter generates cache file name. In my cache 1580e4c2413cb09f6ed3bc7fae8cee45 for currency and d7e2452b0424f859e1a5984bd26cbd6c for category.
I hope this explanation makes sense and I hope most of the codeigniter developer having this problem which need to be sort it out.
Thanks,
Ali
In Codeigniter, you can clear the cache of DB using the table name
like
$this->db->cache_delete('currency');
$this->db->cache_delete('category');
OR two table cache at the same time
$this->db->cache_delete('currency','category');
EDIT :
CodeIgniter save filename by md5() encryption of SQL query
public function cacheAllCurrencies(){
$this->db->cache_on();
$this->db->select("name,icon,currency_code");
$this->db->from("currency");
$this->db->where("status='Active'");
//here you get filename
$file_name=md5($this->db->get_compiled_select());
$cache_currency_result = $this->db->get()->result();
$this->db->cache_off();
return $cache_currency_result;
}
I want to cache a query in CodeIgniter. What I did for my test is make a controller, that I named show.php:
class Show extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('rejaal_show');
}
public function _remap($method = '',$param = array())
{
$method = intval($method);
$this->output->cache(5);
var_dump ($this->rejaal_show->temp($method));
}
}
And a model that I named rejaal_show.php:
public function temp($id)
{
$this->db->cache_on();
$this->db->where('id',$id);
$query = $this->db->get('system_store_table');
return $query->result();
}
When I call http://localhost/rejaal/show/1 for the first time, it will show a result, but when I call it for the second time, it does not show anything.
I should delete the query cache file to show it again? How should I solve this problem?
With special thanks for your attention.
Can you confirm that you have set $db['default']['cachedir'] to the path of a writable folder in application/config/database.php and that when the query is first run it creates a cache file in there?
The only other reason I can think of for it failing is by your use of the _remap override. I have not used db caching using _remap, but know that CodeIgniter creates a folder called controller+action in your cache folder, and might not be handled very well if using remap? Someone correct me if I am wrong about this.
In the CodeIgniter User Guide page for Web Page Caching, it says:
Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for your controller with a view.
Do your var_dump inside a view.
I'm running CodeIgniter 1.7.3, Datamapper DMZ 1.7.1 (and no, upgrading is not an option), MySQL 5.1, and the Cron Job Boostrapper for an application I'm building. I'm attempting to extract information from an XML file and save it into a database. Getting the data works just fine, as does getting data from the database, so I know it's neither an issue with the database connection, nor the XML file.
$this->site = $this->site->get_by_short_name('site');
//Load the XML files into variables so we can do stuff with them.
$doctors = simplexml_load_file(realpath('../xml/doctors.xml'));
foreach ($doctors->children() as $doctor) {
$dr = new Doctor();
$attrs = $doctor->attributes();
/* See if the Doctor already exists. If so, update it.
* Datamapper won't update fields that don't change, so if nothing's
* changed, then the DB call won't be made.
*/
$dr->get_by_drkey($attrs['Key']);
$dr->drkey = $attrs['Key'];
$dr->first_name = $doctor->FirstName;
$dr->middle_name = $doctor->MiddleName;
$dr->last_name = $doctor->LastName;
$dr->long_name = $doctor->LongName;
$dr->degrees = $doctor->Degrees;
$dr->pic = $doctor->ImageURL;
$dr->save($this->site);
}
I've checked the return value of $dr->save($this->site) and it's coming back as true ("successful save"), but the data isn't saving, and there's no error. I've tried without the relation (removed the requirement for it in the database), so it should save without error, but it still doesn't save. I also double-checked the relationship setup in the models and they're fine.
I also tried bypassing Datamapper and doing a straight $this->db->insert('doctors',$data) with the data converted to an array, but the data still doesn't save. I've also tried running it from the browser (bypassing the bootstrapper) to see if the issue had to do with running from the command line, but that also didn't work. I'm also not autoloading any session or authentication libraries, so that known issue with the bootstrapper isn't being triggered.
Does anyone have any insight into why this might not be working?
I've found what was going on. It turns out that the attributes of the SimpleXML objects (the individual records) weren't getting picked up by Datamapper as strings, so they weren't getting escaped, and MySQL was choking. Typecasting them when setting the model object's values ($dr->first_name = (string)$doctor->First_Name;) fixed this problem.
I was able to get the insert query through $dr->check_last_query() after the object attempts to save.