Using Memcached to Cache Results from Model :: find ()

I want to save the DocumentSet returned from Model :: find () to memcached. However, I get MongoException below when I try to work with the results after retrieving them from the cache. In particular, when using foreach, an exception is thrown when calling if ($this->_resource->hasNext()) on line 63 \ data \ source \ mongo_db \ ​​Result.php

MongoException

MongoCursor was not properly initialized by its constructor

I understand why this is so.

My question is, is there anyway to preinstall Model :: find () or create my own DocumentSet so that I can work with the data? Usually I just convert it to an array and store it in the cache. However, I need access to some of the Model methods that I wrote (for example: Customer :: fullName ())

Update . I found a bit of work, but this is not normal. I save the results of Model :: find () as an array in the cache $result->to('array') . Then, after extracting, I go through $ results and populate a new array Model::create($result, array("exists" => true) for each $ result;

+4
source share
1 answer

A DocumentSet returned by Model::find contains the Mongo db cursor. It does not load all the data from the database until the elements are iterated. As each element is iterated, a Document is created and cached in memory to a DocumentSet. The php built-in function iterator_to_array() can be used to turn a DocumentSet into an array of documents that you could cache.

As you noted in your update, you can also use ->to('array') to prepare for caching, and then Model::create() to create it. One caveat with this method: when using ->to('array') it also throws MongoId and MongoDate objects on strings and integers respectively. If you defined $_schema for your model and set the types 'id' and 'date' , they will be returned to the original MongoId and MongoDate objects in the document returned by Model::create() . If you do not have a schema for all of your fields, this can be a problem. I have a recent transfer request that tries to do ->to('array') without using my own mongo objects (also fixes the problem with mongo objects that are always discarded when inside arrays of subdocuments).

FWIW, I really prefer to save only the data in the cache, because this is less space than serializing the whole php object, and avoids possible problems with undefined classes or other elements that are not initialized when extracting an element from the cache.

I have not tried this ... but I would have thought that you could create a cache strategy class that takes care of this transparently for you. Another example of great concern, which was to create lithium in a very flexible and powerful structure. http://li3.me/docs/lithium/storage/cache/strategy

+4
source

Source: https://habr.com/ru/post/1432491/


All Articles