Buy Access to Course
12.

Pagination & Foundry Fixtures

|

Share this awesome video!

|

Keep on Learning!

With a Subscription, click any sentence in the script to jump to that part of the video!

Login Subscribe

We're going to start doing more with our API... so it's time to bring this thing to life with some data fixtures!

For this, I like to use Foundry along with DoctrineFixturesBundle. So, run

composer require foundry orm-fixtures --dev

to install both as dev dependencies. Once that finishes, run

php bin/console make:factory

Adding the Foundry Factory

If you haven't used Foundry before, for each entity, you create a factory class that's really good at creating that entity. I'll hit zero to generate the one for DragonTreasure.

The end result is a new src/Factory/DragonTreasureFactory.php file:

74 lines | src/Factory/DragonTreasureFactory.php
// ... lines 1 - 2
namespace App\Factory;
use App\Entity\DragonTreasure;
use App\Repository\DragonTreasureRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;
/**
* @extends ModelFactory<DragonTreasure>
*
* @method DragonTreasure|Proxy create(array|callable $attributes = [])
* @method static DragonTreasure|Proxy createOne(array $attributes = [])
* @method static DragonTreasure|Proxy find(object|array|mixed $criteria)
* @method static DragonTreasure|Proxy findOrCreate(array $attributes)
* @method static DragonTreasure|Proxy first(string $sortedField = 'id')
* @method static DragonTreasure|Proxy last(string $sortedField = 'id')
* @method static DragonTreasure|Proxy random(array $attributes = [])
* @method static DragonTreasure|Proxy randomOrCreate(array $attributes = [])
* @method static DragonTreasureRepository|RepositoryProxy repository()
* @method static DragonTreasure[]|Proxy[] all()
* @method static DragonTreasure[]|Proxy[] createMany(int $number, array|callable $attributes = [])
* @method static DragonTreasure[]|Proxy[] createSequence(array|callable $sequence)
* @method static DragonTreasure[]|Proxy[] findBy(array $attributes)
* @method static DragonTreasure[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
* @method static DragonTreasure[]|Proxy[] randomSet(int $number, array $attributes = [])
*/
final class DragonTreasureFactory extends ModelFactory
{
// ... lines 32 - 36
public function __construct()
{
parent::__construct();
}
// ... lines 41 - 46
protected function getDefaults(): array
{
return [
'coolFactor' => self::faker()->randomNumber(),
'description' => self::faker()->text(),
'isPublished' => self::faker()->boolean(),
'name' => self::faker()->text(255),
'plunderedAt' => \DateTimeImmutable::createFromMutable(self::faker()->dateTime()),
'value' => self::faker()->randomNumber(),
];
}
// ... lines 58 - 61
protected function initialize(): self
{
return $this
// ->afterInstantiate(function(DragonTreasure $dragonTreasure): void {})
;
}
protected static function getClass(): string
{
return DragonTreasure::class;
}
}

This class is just really good at creating DragonTreasure objects. It even has a bunch of nice random data ready to be used!

To make this even fancier, I'm going to paste over with some code that I've dragon-ized. Oh, and we also need a TREASURE_NAMES constant... which I'll also paste on top. You can grab all of this from the code block on this page.

74 lines | src/Factory/DragonTreasureFactory.php
// ... lines 1 - 29
final class DragonTreasureFactory extends ModelFactory
{
private const TREASURE_NAMES = ['pile of gold coins', 'diamond-encrusted throne', 'rare magic staff', 'enchanted sword', 'set of intricately crafted goblets', 'collection of ancient tomes', 'hoard of shiny gemstones', 'chest filled with priceless works of art', 'giant pearl', 'crown made of pure platinum', 'giant egg (possibly a dragon egg?)', 'set of ornate armor', 'set of golden utensils', 'statue carved from a single block of marble', 'collection of rare, antique weapons', 'box of rare, exotic chocolates', 'set of ornate jewelry', 'set of rare, antique books', 'giant ball of yarn', 'life-sized statue of the dragon itself', 'collection of old, used toothbrushes', 'box of mismatched socks', 'set of outdated electronics (such as CRT TVs or floppy disks)', 'giant jar of pickles', 'collection of novelty mugs with silly sayings', 'pile of old board games', 'giant slinky', 'collection of rare, exotic hats'];
// ... lines 33 - 46
protected function getDefaults(): array
{
return [
'coolFactor' => self::faker()->numberBetween(1, 10),
'description' => self::faker()->paragraph(),
'isPublished' => self::faker()->boolean(),
'name' => self::faker()->randomElement(self::TREASURE_NAMES),
'plunderedAt' => \DateTimeImmutable::createFromMutable(self::faker()->dateTimeBetween('-1 year')),
'value' => self::faker()->numberBetween(1000, 1000000),
];
}
// ... lines 58 - 72
}

Ok, so this class is done. Step two: to actually create some fixtures, open src/DataFixtures/AppFixtures.php. I'll clear out the load() method. All we need is: DragonTreasureFactory::createMany(40) to create a healthy trove of 40 treasures:

16 lines | src/DataFixtures/AppFixtures.php
// ... lines 1 - 2
namespace App\DataFixtures;
use App\Factory\DragonTreasureFactory;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
DragonTreasureFactory::createMany(40);
}
}

Let's try this thing! Back at your terminal, run:

symfony console doctrine:fixtures:load

Say "yes" and... it looks like it worked! Back on our API docs, refresh... then let's try the GET collection endpoint. Hit execute.

We have Pagination!

Oh, so cool! Look at all those beautiful treasures! Remember, we added 40. But if you look closely... even though the IDs don't start at 1, we can see that there are definitely less than 40 here. The response says hydra:totalItems: 40, but it only shows 25.

Down here, this hydra:view kind of explains why: there's built-in pagination! Right now we're looking at page 1.. and we can also see the URLs for the last page and the next page.

So yes, API endpoints that return a collection need pagination... just like a website. And with API Platform, it just works.

To play with this, let's go to /api/treasures.jsonld. This is page 1... and then we can add ?page=2 to see page 2. That's the easiest thing I'll do all day.

Digging Into API Platform Configuration

Now if you need to, you can change a bunch of pagination options. Let's see if we can tweak the number of items per page from 25 to 10.

To start digging into the config, open up your terminal and run:

php bin/console debug:config api_platform

There are a lot of things that you can configure on API Platform. And this command shows us the current configuration. So for example, you can add a title and description to your API. This becomes part of the OpenAPI Spec... and so it shows up on your documentation.

If you search for pagination - we don't want the one under graphql... we want the one under collection - we can see several pagination-related options. But, again, this is showing us the current configuration... it doesn't necessarily show us all possible keys.

To see that, instead of debug:config, run:

php bin/console config:dump api_platform

debug:config shows you the current configuration. config:dump shows you a full tree of possible configuration. Now... we see pagination_items_per_page. That sounds like what we want!

This is actually really cool. All of these options live under something called defaults. And these are snake-case versions of the exact same options that you'll find inside the ApiResource attribute. Setting any of these defaults in the config causes that to be the default value passed to that option for every ApiResource in your system. Pretty cool.

So, if we wanted to change the items per page globally, we could do it with this config. Or, if we want to change it only for one resource, we can do it above the class.

Customizing Max Items Per Page

Find the ApiResource attribute and add paginationItemsPerPage set to 10:

163 lines | src/Entity/DragonTreasure.php
// ... lines 1 - 18
#[ApiResource(
// ... lines 20 - 34
paginationItemsPerPage: 10
)]
class DragonTreasure
{
// ... lines 39 - 161
}

Again, you can see that the options we already have... are included in the defaults config.

Move over and head back to page 1. And... voilà! A much shorter list. Also, there are now 4 pages of treasure instead of 2.

Oh, and FYI: you can also make it so that the user of your API can determine how many items to show per page via a query parameter. Check the documentation for how to do that.

Ok, now that we have a lot of data, let's add the ability for our Dragon API users to search and filter through the treasures. Like maybe a dragon is searching for a a treasure of individually wrapped candies among all this loot. That's next.