A free and open-source book on ZF3 for beginners

12.11. Deleting a Post

In this section, we will implement the deleteAction() action of the PostController. This action will allow to delete certain post given its ID. The action will take ID as a GET variable, look if a post with such ID exists, and if exists, deletes the post, its related comments and tag associations. Site visitor will be able to trigger the action by entering the following URL in browser's navigation bar: http://localhost/posts/delete/<id>, where <id> is the unique identifier of the post. Finally, the action redirects the site visitor to the Admin page.

12.11.1. Modifying PostManager

First, we'll add the removePost() method to the PostManager service. This method will remove the post and its associated comments. It will also remove associations between post and tags.

class PostManager
  // Removes post and all associated comments.
  public function removePost($post) 
    // Remove associated comments
    $comments = $post->getComments();
    foreach ($comments as $comment) {
    // Remove tag associations (if any)
    $tags = $post->getTags();
    foreach ($tags as $tag) {

In the code above, we first retrieve all comments associated with the post using the getComments() method of the Post entity. Then we call EntityManager's remove() method and pass it each comment that we want to remove.

Next, we get all tags associated with the post by calling Post's getTags() method. We remove association between the post and tag (but not tag itself!) with the help of the Post's removeTagAssociation() method (see below for the code of the method).

Finally, we remove the post itself by calling the EntityManager's remove() method. We apply changes to database with the flush() method.

And here is the code of the Post::removeTagAssociation() method:

// Removes association between this post and the given tag.
public function removeTagAssociation($tag) 

12.11.2. Adding Controller Action

The PostController::deleteAction() method retrieves the ID of the post to be removed, checks whether this is a valid post ID. If so, it calls the PostManager::removePost() method to remove the post and apply changes to database. Finally, it redirects the site visitor to the Admin page.


class PostController extends AbstractActionController 
  // This "delete" action displays the Delete Post page.
  public function deleteAction()
    $postId = $this->params()->fromRoute('id', -1);
    $post = $this->entityManager->getRepository(Post::class)
    if ($post == null) {
    // Redirect the user to "index" page.
    return $this->redirect()->toRoute('posts', ['action'=>'admin']);