Skip to content

Set up an MVC controller

A controller groups actions. Register it under controllers in your module configuration. A controller without dependencies can use InvokableFactory.

mvc/module/Application/src/Controller/HelloController.php
<?php

declare(strict_types=1);

namespace Application\Controller;

use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;

/** @api */
final class HelloController extends AbstractActionController
{
    public function greetAction(): Response
    {
        $response = new Response();
        $response->setContent('Hello');

        return $response;
    }
}
mvc/module/Application/config/hello.config.php
<?php

declare(strict_types=1);

namespace Application;

use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;

return [
    'router'      => [
        'routes' => [
            'hello' => [
                'type'    => Literal::class,
                'options' => [
                    'route'    => '/hello',
                    'defaults' => ['controller' => Controller\HelloController::class, 'action' => 'greet'],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\HelloController::class => InvokableFactory::class,
        ],
    ],
];

More in the laminas-mvc documentation.