PHP code example of webfactory / http-cache-bundle

1. Go to this page and download the library: Download webfactory/http-cache-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webfactory / http-cache-bundle example snippets




// ...
use Webfactory\HttpCacheBundle\NotModified\Attribute\ReplaceWithNotModifiedResponse;

class MyController {
    // Routing etc. configuration skipped for brevity
     
    #[ReplaceWithNotModifiedResponse(["@app_caching_post", "@app_caching_latest_posts"])]
    public function indexAction(Post $post): Response
    {
        // your code
        // won't be called in case of a 304
    }
}


// src/Caching/PostsLastModifiedDeterminator.php
namespace App\Caching;

use App\Entity\PostRepository;
use Symfony\Component\HttpFoundation\Request;
use Webfactory\HttpCacheBundle\NotModified\LastModifiedDeterminator;

/**
 * Returns the publishing date of the latest posts.
 */
final class PostsLastModifiedDeterminator implements LastModifiedDeterminator
{
    public function __construct(
        private readonly BlogPostRepository $blogPostRepository,
    ) {
    
    public function getLastModified(Request $request): ?\DateTime
    {
        $post = $this->blogPostRepository->findLatest();
        
        return $post?->getPublishingDate();
    }
}



namespace src\Controller;

use Symfony\Component\HttpFoundation\Response;
use Webfactory\HttpCacheBundle\NotModified\Attribute\ReplaceWithNotModifiedResponse;

final class MyController
{
     #[ReplaceWithNotModifiedResponse([...])]
    public function indexAction()
    {
        // ...
        return new Response(...);
    }
}