📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Zend Framework / Laminas Controllers in Laminas

Controllers in Laminas

6 min read Quiz at the end
Write action controllers: access route params, handle forms, return ViewModel or JsonModel.

Controllers

namespace BlogController;

use LaminasMvcControllerAbstractActionController;
use LaminasViewModelViewModel;
use LaminasViewModelJsonModel;

class PostController extends AbstractActionController {
    public function __construct(private PostTable $postTable) {}

    public function indexAction(): ViewModel {
        return new ViewModel([
            "posts" => $this->postTable->fetchAll(),
        ]);
    }

    public function viewAction(): ViewModel {
        $id   = (int) $this->params()->fromRoute("id", 0);
        $post = $this->postTable->getPost($id);
        return new ViewModel(["post" => $post]);
    }

    public function addAction() {
        $form    = new PostForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = new Post();
            $form->setInputFilter($post->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $post->exchangeArray($form->getData());
                $this->postTable->savePost($post);
                return $this->redirect()->toRoute("blog");
            }
        }
        return new ViewModel(["form" => $form]);
    }

    // JSON response
    public function apiAction(): JsonModel {
        return new JsonModel(["posts" => $this->postTable->fetchAll()->toArray()]);
    }
}
Topic Quiz · 2 questions

Test your understanding before moving on

1. What class do Laminas action controllers extend?
💡 LaminasMvcControllerAbstractActionController is the base class.
2. How are URL parameters accessed in a Laminas controller?
💡 $this->params()->fromRoute("id") reads parameters from the matched route.