s
Home/Blog/Stripe & Symfony: Performance verbessern (Cache)/

SymfonyE-CommerceStripeTechSnippetPHP

26 Mar 21

Stripe & Symfony: Performance verbessern (Cache)

A little tip to improve performance with Stripe and Symfony.

If you frequently load data from Stripe in your application, for example to retrieve metadata from subscriptions, you can use the built-in Symfony cache to achieve a significant speedup:

<?php
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Stripe\Customer;
use App\Entity\User;
//...

public function getStripeDataForUser(User $user, CacheInterface $cache)
{
    return $cache->get('stripedata-' . $user->getId(), function (ItemInterface $item) use ($user) {
        $item->expiresAfter(1800);

        try {
            $data = Customer::retrieve($user->getCustomerId());
            
            // ...
            
            return $data;
        } catch (\Exception $e) {
            // ...
        }
    }
}

This way you don't have to send a request to the Stripe API every time and your application will run much faster.