Skip to content

PageParameters Service

PageParameters is a service class that can be accessed and mutated by the page as well as all individual sections on the page. This makes it a powerful way to share data between different parts of the page without having to query the database multiple times.

It is located in ./src/Service/PageParameters.php and is automatically made available to PageType and SectionType controllers.


Adding To PageParameters

Because we want to only pull data when it is needed, we generally handle new data by providing a loader method and a getter method. In the example below, you will see how we can load an animal name from the database only when necessary, returning the previous result if it has already been loaded:

Example

Php

<?php

// ...

class PageParameters extends AbstractController
{
    private ?string $animalName = null;

    // ...

    // Loader method to fetch the animal name from the database.
    public function loadAnimalName(): string
    {
        $resultsFromDatabase = /* do database query to get animal name */;
        $this->animalName = $resultsFromDatabase['name'] ?? null;
        return $this->animalName;
    }

    // Getter method to fetch the animal name only when needed.
    public function getAnimalName(): string
    {
        return $this->animalName ?? $this->loadAnimalName();
    }
}

Reading From PageParameters

SectionType controllers are passed PageParameters by reference via the handlePageSectionRequest method. You can access the values directly in this method to read the animal name:

SectionType Example

<?php

// ...

class SomeSectionType extends AbstractSection
{

    // ...

    final public function handlePageSectionRequest(
        Request        $request,
        Page           $page,
        Section        $section,
        PageParameters $pageParameters,
    ): Response {
        // loads the animal name if it hasn't been loaded yet
        $animalName = $pageParameters->getAnimalName();

        // ...
    }

}

Because PageParameters is just a Symfony service, you can also access it from other controllers by injecting it into the controller's constructor:

Misc Controller Example

<?php

// ...

use App\Service\PageParameters;

class SomeOtherController extends AbstractController
{
    public function __construct(
        private PageParameters $pageParameters,
    ){}

    public function someMethod(): Response
    {
        // loads the animal name if it hasn't been loaded yet
        $animalName = $this->pageParameters->getAnimalName();

        // ...
    }
}