Home > Back-end >  Server-sent events in PHP (without echo or print)
Server-sent events in PHP (without echo or print)

Time:05-14

We have built a prototype application in PHP and JS using Server-Sent Events (single AJAX requests, multiple streamed events sent by event handlers in PHP). Essentially the PHP at some point is using echo to send data back, much like this example: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#sending_events_from_the_server i.e.

echo "event: ping\n";

However the platform we are building for (Magento) has strict coding standards that prohibit echo and print (and print_r and var_dump). Is there any way around this aside from scrapping SSE and setting up AJAX polling?

CodePudding user response:

Well, I think you have 2 ways of "echoing" something in Magento.

1. Adding your PHP file to /pub

Yes, you can run you custom PHP file to "echo" whatever you want. But you will need to place it under <magento folder>/pub/yourfile.php.

If you're using nginx you will also need to create an exception for your file. Otherwise, Magento's routing will be used.

For doing that, find something like location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check)\.php$ { in your nginx file, and add yourfile.php there.

For example:

location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check|yourfile)\.php$ {.

Once your file is there, it will be served under yourstore.com/yourfile.php or yourstore.com/pub/yourfile.php (in case you are wrongfully exposing the root directory).

2. The magento way - create a controller

You will need to create a module and a controller. There are plenty of tutorials out there explaining how to create them.

Here you can find how to create the basic module's structure.

And in this other article you can see how to create different controllers with different types of return.

CodePudding user response:

You can use ob_start() and ob_end_flush() it behaves similar to how a print or echo would when interacting with the event stream. See link below for example.

Example: ServerSentEvents.php

  • Related