简体   繁体   中英

yii2 page caching for single posts

I have blog via yii2 and using page caching

    'class' => 'yii\filters\PageCache',
    'only' => ['view','video'],
    'duration' => 900,
    'dependency' => [
        'class' => 'yii\caching\DbDependency',
         'sql' => '?',
    ],

my post table has primary key as id ; how to I set sql as separate page cache per post id ? thank you guy .

Just pass the current ID to it and yes, you can do it, use the enabled property and variation like this

[
            'enabled' => Yii::$app->request->isGet && Yii::$app->user->isGuest,
            'class' => 'yii\filters\PageCache',
            'only' => ['index'],
            'duration' => 900,
            'variations' => [
                Yii::$app->request->get('id')
            ]
]

This ensures that it will cache only get requests for non logged in users per post ID, you don't want to cache other request than get or logged in users if they can do some things like commenting and see per user data (login name etc.)

You can even use a more advanced config if you like eg. dynamic placeholder with page cache to allow caching even for authenticated users, just check the docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM