Methods, request, links and redirects
One controller usually has several methods: one shows the page, another receives a form. Each method needs to read what came in the request and often to build a link to another page. Three registry objects do this: $this->request, $this->url and $this->response.
A second method
Add a method to the controller from the previous lesson:
// catalog/controller/information/hello.php
public function about(): void
{
$this->response->setOutput('About this page');
}The method is written in the address after a dot: index.php?route=information/hello.about. Only public methods can be opened by address.
Reading the request
public function index(): void
{
$name = $this->request->get['name'] ?? 'guest';
$this->response->setOutput('Hello, ' . $name . '!');
}Open index.php?route=information/hello&name=Anna — the page shows «Hello, Anna!». Without the parameter it shows «Hello, guest!».
| Property | What is in it |
|---|---|
$this->request->get | Parameters from the address |
$this->request->post | Form fields |
$this->request->files | Uploaded files |
$this->request->cookie | Cookies |
$this->request->server | Server data: method, IP address, headers |
These are plain arrays. A missing key causes a warning, so always give a default with ??. Numbers are cast: (int) ($this->request->get['product_id'] ?? 0).
The engine passes strings from the request through htmlspecialchars(), so <b> arrives as <b>.
Links
Addresses are not assembled by hand. The link() method takes the route and the parameters:
$language = 'language=' . $this->config->get('config_language');
$about = $this->url->link('information/hello.about', $language);
$product = $this->url->link('product/product', $language . '&product_id=42');$about contains http://shop.test/index.php?route=information/hello.about&language=en-gb. If SEO URLs are turned on, the same call returns the short address. In version 4 the language parameter is passed in every storefront link.
Redirect
public function old(): void
{
$this->response->redirect($this->url->link('information/hello', 'language=' . $this->config->get('config_language')));
}Open index.php?route=information/hello.old — the browser goes to the main method of the page. redirect() ends the request itself, no exit is needed after it.
Page not found
When the requested record does not exist, the controller sends status 404:
$this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . ' 404 Not Found');After that it outputs a page as usual — the core does it with the error/not_found template.
Common mistake
A helper method is declared public — and anyone can call it by address: index.php?route=information/hello.cleanup. Everything that is not a page or a form handler must be private or protected.