如何在一个动作中使httpcache无效?

时间:2018-06-16 18:28:29

标签: php symfony caching cache-control

我只是采取行动:

/**
 * @Route("/", name="index")
 */
public function indexAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $news = $em->getRepository('AppBundle:News')->findBy(array('main' => 1));
    $response = $this->render('index.html.twig', array('news' => $news));

    $response->setSharedMaxAge(3600);
    $response->headers->addCacheControlDirective('must-revalidate', true);

    return $response;
}

运行良好,网站已缓存,但我想在模块新闻的管理面板中更改它,使此缓存无效并让所有用户看到更改。

/**
 * @Route("/admin/save-news", name="admin_save_news")
 */
public function saveNewsAction(Request $request)
{
    //...
    $em->persist($news);
    $em->flush();
    //how to invalidate here?
    //...
}

我试过了:

protected function invalidateCache($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PURGE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);

    curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $status == 200;
}

$ url ='http://example.com/';

但它不起作用,另外很奇怪......它一定是一种更好的方式

0 个答案:

没有答案