CakePHP 3: Caching database object in component

620 views Asked by At

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!

1

There are 1 answers

4
Greg Schmidt On BEST ANSWER

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.)