Zend Basic Tutorial
Zend Forms
Zend Database
Zend Advanced
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.
Zend controllers extend Laminas\Mvc\Controller\AbstractActionController.
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!',
]);
}
}
'controllers' => [ 'factories' => [ Controller\MainController::class => Laminas\ServiceManager\Factory\InvokableFactory::class, ], ],
Each public method ending with Action is an action.
indexAction() → URL: /aboutAction() → URL: /aboutYou use ViewModel to send data to a .phtml file:
return new ViewModel([ 'message' => 'Welcome to Zend!', ]);
use Laminas\View\Model\ViewModel;
public function indexAction()
{
return new ViewModel(); // renders 'main/index.phtml'
}
public function aboutAction()
{
return new ViewModel(['message' => 'About Page']);
}
public function aboutAction()
{
return $this->redirect()->toRoute('dashboard'); // route name mention here
}
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.
|
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 |