1

i'm trying to save an database object from the (plugin) component into the CakePHP Cache.

This works ( note the toArray() )

        $domains = Cache::read('domains', 'long');

        if ($domains === false) {

            $domainsTable = TableRegistry::get('DomainManager.Domains');
            $domains = $domainsTable->find('all', ['fields' => ['id', 'name']]);
            $domains = $domains->toArray();

            Cache::write('domains', $domains, 'long');
            return $domains;
        }

But this fails:

        $domains = Cache::read('domains', 'long');

        if ($domains === false) {

        $domainsTable = TableRegistry::get('DomainManager.Domains');
        $domains = $domainsTable->find('all', ['fields' => ['id', 'name']]);

        Cache::write('domains', $domains, 'long');
        return $domains;
    }

The error given from CakePHP is Error: You cannot serialize or unserialize PDO instances

Sorry if i'm just doing something wrong, i just switched from Cake2 to Cake3 and could nothing find in the Documentation.

Thanks for any glues!

Kneecht
  • 93
  • 9

1 Answers1

1

The find function does not return results, it returns a query object that you can use to fetch results. Calling toArray on this will retrieve all the entities and give you something you can cache. (It can be confusing, as toArray is also used to convert entities into arrays in other situations.)

Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
  • Hi Greg, thanks for your answer. But doesn't the CakePHP Documentation (http://book.cakephp.org/3.0/en/core-libraries/caching.html#writing-to-a-cache) say "Cache::write() can store any type of object and is ideal for storing results of model finds" or does this mean only arrays can be stored in the cache? It could be that i'm just misreading the documentation on this. – Kneecht Jan 26 '16 at 15:32
  • "Results" typically means the rows returned by the database. `find` does not return rows, it returns a query object that can be used to retrieve the rows, in various ways. You can store lots of things in the cache, but query objects are not one of them. – Greg Schmidt Jan 26 '16 at 16:32
  • Okay, thanks! :-) Looks like i should take a deep look into the new ORM once more. – Kneecht Jan 26 '16 at 16:49
  • I found something in the documentation (http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#using-finders-to-load-data), `$query->toArray()` executes the query, as does `$query->all()`. Thanks Greg for the hint! – Kneecht Jan 26 '16 at 16:54