Symfony HTTP client
I am currently developing a very simple app which offers you the possibility to create question-answer flipping cards, creating thus some kind of funny Trivia to practice on any topic you want to apply it to. As a user, you create first the question-aswear entities which also include category field, and then you can practice them in the playground area, which shows you the question on a hoverable flipping card. It also offers you a textearea which disables 60 seconds after you start typing on it, so that you can write down your answer before actually flipping the card and getting to see the correct one.
In this app, though simple, I wanted to keep a client-web service architecture from the very beginning. The web client contains the views and communicates with the API, which contains the data through Ajax calls. This was working consistently so far. An example of the creation and saving of new question-answer items is:
- When I press on "Create new question" button, I am redirected to question-answer item edition page, where, on every blur event happenning on textareas where the user writes down the relevant data, an ajax call makes a PATCH request to the API, which saves question, answer and category atributes of the entity entered by the user, together with an Auto-Increment Id and a Uuid.
- From the index page, if I click on "I want to practice" button, an ajax call makes a GET request to the API randomizer web service, which randomly chooses an uuid from the database and returns it.
And here is where things get different. When using a Symfony coupled architecture, I could just manage all of this data retrieval through Doctrine within the same project and render a template with parameters. But in this case, I am managing redirects and renderings within the success of the ajax calls, as these redirections are the consequence of successful operations with the API, using the function:
window.location.replace(url);
composer require symfony/http-client
use Symfony\Contracts\HttpClient\HttpClientInterface; class Example { private $client; public function __construct(HttpClientInterface $client) { $this->client = $client; } }
1 2 3 4 5 6 7 | $apiDomain = $this->getParameter('api_host'); $getQuestionServiceUrl = $this->apiDomain.'/v1/Questions/'.$uuid $response = $this->client->request( 'GET', '$getQuestionServiceUrl' |
1 2 3 4 5 6 | return new JsonResponse([ 'uuid' => $uuid, 'question' => $this->randomQuestionAndAnswerItem->getQuestion(), 'answer' => $this->randomQuestionAndAnswerItem->getAnswer(), 'category' => $this->randomQuestionAndAnswerItem->getCategory(), ]); |
$question = $jsonDecodedResponse['question']; $answer = $jsonDecodedResponse['answer']; $category = $jsonDecodedResponse['category'];
Comments
Post a Comment