Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Controllers and actions

A controller is a class that receives a request and returns a response. Its public methods ending in Action are called actions: one action is one page. A module's controllers live in module/<Module>/src/Controller.

Creating a controller

There is no command for it. Create the folder module/Blog/src/Controller and the file PostController.php inside it:

// module/Blog/src/Controller/PostController.php
namespace Blog\Controller;
 
use Laminas\Mvc\Controller\AbstractActionController;
 
class PostController extends AbstractActionController
{
    public function indexAction()
    {
        $response = $this->getResponse();
        $response->setContent('List of posts');
 
        return $response;
    }
}

The class extends AbstractActionController, which gives the controller the getResponse() method and other tools. The action writes text into the response object and returns it.

Registration

Laminas does not create a controller until it knows how. Add a controllers section to module/Blog/config/module.config.php, next to the router section:

// module/Blog/config/module.config.php
// at the top of the file: use Laminas\ServiceManager\Factory\InvokableFactory;
'controllers' => [
    'factories' => [
        Controller\PostController::class => InvokableFactory::class,
    ],
],

On the left is the controller class, on the right a factory — a class that knows how to create it. InvokableFactory is the simplest factory: it calls new PostController() with no arguments.

Open http://localhost:8080/blog — the page shows the text "List of posts".

Action names

The route names the action by a short name, and the method gets the Action suffix:

action value in the routeController method
indexindexAction()
viewviewAction()
addaddAction()

An action with a parameter

The blog/view route passes the id parameter. Add a second action to the controller:

public function viewAction()
{
    $id = (int) $this->params()->fromRoute('id');
 
    $response = $this->getResponse();
    $response->setContent("Post $id");
 
    return $response;
}

$this->params()->fromRoute('id') returns the parameter value from the address. At /blog/5 the page shows "Post 5".

What an action returns

Returning a ready response with text is convenient only for a quick check. Normally an action returns a ViewModel object with data, and a view script builds the HTML — the next lesson is about that.

Common mistake

A controller named in a route but missing from controllers.factories cannot be created. The site answers with a 404 error explaining that the controller could not be mapped to an existing class. Every new controller means a new line in the controllers section.

Thanks for reading!

Donate to the site — we work hard for you.