Advertisement

Google Ad Slot: content-top

Zend Controllers


What is a Controller?

A controller in Zend Framework is a PHP class that handles HTTP requests and returns responses. Each method inside the controller is called an action.

Think of a controller as the brain between the user (browser) and your application logic.

Controller Structure 

Zend controllers extend Laminas\Mvc\Controller\AbstractActionController.

📌 Example: MainController.php (module\Application\src\Controller\MainController.php)

namespace Application\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;

class MainController extends AbstractActionController
{
  public function indexAction()
  {
    return new ViewModel([
      'message' => 'Welcome to Zend!',
    ]);
  }
}

 Registering Controller – (module/Application/config/module.config.php)

'controllers' => [
  'factories' => [
    Controller\MainController::class => Laminas\ServiceManager\Factory\InvokableFactory::class,
  ],
],

How Actions Work

Each public method ending with Action is an action.

  • indexAction() → URL: /
  • aboutAction() → URL: /about

Passing Data to View

You use ViewModel to send data to a .phtml file:

return new ViewModel([
  'message' => 'Welcome to Zend!',
]);

Controller Action Return Types:

1.Normal website pages(Web)

use Laminas\View\Model\ViewModel;

public function indexAction()
{
    return new ViewModel(); // renders 'main/index.phtml'
}

public function aboutAction()
{
    return new ViewModel(['message' => 'About Page']);
}


3.Redirect to another route

public function aboutAction()
{
    return $this->redirect()->toRoute('dashboard'); // route name mention here
}


2.JsonModel(REST API)

use Laminas\View\Model\JsonModel;

public function getListAction() {
    return new JsonModel(['data' => ['a', 'b', 'c']]);
}

public function getAction($id) {
    return new JsonModel(['id' => $id]);
}

Each method ending with Action() is an action method.


Controller Action Return Types

Return Type

Description

new ViewModel()

Returns view data and renders view template

$this->redirect()->toRoute(...)

Redirect to another route

JsonModel

Return JSON response for APIs