Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

symfony4 - 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.

question from:https://stackoverflow.com/questions/65896281/how-to-subscribe-the-api-fetched-data-in-shopware-6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 MyPluginStruct;

use ShopwareCoreFrameworkStructStruct;

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...