D
D
Dmitry Sidorenko2014-12-21 13:59:31
Yii
Dmitry Sidorenko, 2014-12-21 13:59:31

How to configure Yii2 caching when using only yii\db\Connection?

I use not all Yii2 but only yii\db\Connection, and therefore all the links indicated in it.
cache(3600) should cache the query for an hour, but always prints the actual data from the database (I change it manually for testing)
Here is the PHP code:
<?php
define('YII_DEBUG', false);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . './core/classes/Yii2/Yii.php');
$connection = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=tt',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
$connection->open();
$q = "
$a = $connection->createCommand($q)->cache(3600)->queryAll();
print_r($a);
?>
/*
Works and outputs:
0 => [id_category_type=>1, name=>Name ],[...],[...]...
*/
But if I use caching in the standard Yii2 model (inherited from \yii\db\ActiveRecord) then everything works fine.
Yii2 is positioned as a framework whose classes can be used separately in different projects.
Please tell me how can I achieve caching, maybe I missed an important parameter in the config?
Thank you for your time and attention!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Zelenin, 2014-12-21
@sidorenkoda

you didn't configure caching itself.

Yii::createObject('cache',[
'class' => ...,
....
]);

UPD:
<?php

define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require_once __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';

$container = new \yii\di\Container;

$container->set('cache', [
    'class' => 'yii\caching\FileCache',
    'cachePath' => $_SERVER['DOCUMENT_ROOT'] . '/cache/',
    'cacheFileSuffix' => '.xxx',
]);
$cache = $container->get('cache');

$container->set('connection', [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2-app',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
    'queryCache' => $cache
]);

$connection = $container->get('connection');
$connection->open();
$q = "SELECT * FROM user_user";
$a = $connection->createCommand($q)->cache(45)->queryAll();

E
Ekstazi, 2014-12-22
@Ekstazi

It's all about DI, I already talked about this yesterday.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question