Search code examples
symfony4shopware

How to subscribe the API fetched data in Shopware 6?


I am a beginner to Shopware. I need to fetch data from an external API and display it in Shopware storefront. So far I have created a REST API inside the folder Core/Api/ where I have written all the http-client codes to fetch data.

My route is something like this:

@Route("/api/v{version}/_action/rest-api-handling/test", name="api.custom.rest_api_handling.test", methods={"GET"})

From the documentation https://docs.shopware.com/en/shopware-platform-dev-en/how-to/register-subscriber , I need to create a subscriber to dislay data.

class FooterSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            StorefrontRenderEvent::class => 'onFooterPageLoaded'
        ];
    }

    public function onFooterPageLoaded(StorefrontRenderEvent $event): array
    {
        return [
            "array"
        ];
    }
}

But I am not sure how can I call my Route.

Can anybody please help me.

Thank You.


Solution

  • I think that you don't need the API route. First of all, API is for admin(back office app) purposes and is not for a storefront.

    You need to move

    all the http-client codes to fetch data

    to some own service. Then you can inject that new service via container to your subscriber and call something like $this->externalApiService->getData() in your onFooterPageLoaded() method.

    To add some data (extend footer data) you need to add extension to pagelet e.g.

    $event->getPagelet()->addExtension('my_data', $data);
    

    Then you need to extend your twig template and access your data by

    page.footer.extensions.my_data
    

    To add array data as an extension you have to define a dummy Struct class

    <?php
    
    namespace MyPlugin\Struct;
    
    use Shopware\Core\Framework\Struct\Struct;
    
    class ApiDataStruct extends Struct
    {
     /**
     * @var array
     */
    protected $data;
    
    /**
     * @return array
     */
    public function getData(): array
    {
        return $this->data;
    }
    
    /**
     * @param array $data
     */
    public function setData(array $data): void
    {
        $this->data = $data;
    }
    

    }

    and then in subscriber create an instance of that object

    $data = new ApiDataStruct();
    $data->setData($this->externalApiService->getData());
    
    $event->getPagelet()->addExtension('my_data', $data);