Hitting DELETE [Raw Symfony 4]
In my opinion DELETE
is the second easiest HTTP verb to implement. Our delete
method will, as the name suggests, let our Symfony 4 API consumer delete an Album
. In the real world, you likely would restrict the DELETE
function to specific users with specific roles.
If your requirements are that you need to restrict who can call the delete
route then please watch this video next.
Let's look at the Behat scenario to refresh our memory of how a DELETE
call should work:
Background:
Given there are Albums with the following details:
| title | track_count | release_date |
| some fake album name | 12 | 2020-01-08T00:00:00+00:00 |
| another great album | 9 | 2019-01-07T23:22:21+00:00 |
| now that's what I call Album vol 2 | 23 | 2018-02-06T11:10:09+00:00 |
Scenario: Can delete an Album
Given I request "/album/3" using HTTP GET
Then the response code is 200
When I request "/album/3" using HTTP DELETE
Then the response code is 204
When I request "/album/3" using HTTP GET
Then the response code is 404
The gist being:
1) Check the album exists 2) Delete the album 3) Confirm the album no longer exists
As our Behat tests are isolated from our implementation, the only way we can do this is to "dogfood" our own API.
Implementing DELETE
Prepare yourself, this code is long and complex:
/**
* @Route(
* "/album/{id}",
* name="delete_album",
* methods={"DELETE"},
* requirements={"id"="\d+"}
* )
* @param int $id
*
* @return JsonResponse
*/
public function delete($id)
{
$existingAlbum = $this->findAlbumById($id);
$this->entityManager->remove($existingAlbum);
$this->entityManager->flush();
return new JsonResponse(
null,
JsonResponse::HTTP_NO_CONTENT
);
}
We've already done all the hard work through implementing the other controller methods.
We re-use the $this->findAlbumById($id)
private method call to ensure any invalid Album
id
requests will throw a 404
.
If the Album
does exist we ask Doctrine to remove / delete the record from the table the next time changes are flushed off to the database.
And on the very next line we call a flush
to ensure the record is immediately deleted.
As there's nothing further to say, we return a 204
/ no content response.
The good news?
We're (almost) done with our basic Symfony 4 API implementation:
php vendor/bin/behat
# ...
12 scenarios (12 passed)
52 steps (52 passed)
0m2.15s (10.68Mb)
There's just one more problem that we need to address. And this is typically only going to affect you once you ship your code off to production. We're going to get on to this in the very next video.