The first controller
A controller is a class that answers a request: it receives the address, prepares the data and returns the page. Every page of the shop is a controller. There is no routes file in OpenCart — the address itself points to the controller file.
Where it lives
Storefront controllers are in catalog/controller/, grouped into folders by topic: product, checkout, account, information.
catalog/controller/
├── common/ header, footer, home page
├── product/ product, category, search
└── information/
└── hello.php the new fileWhile learning, the file is put next to the core controllers. Real code is packaged as an extension — the chapter about extensions moves this page into extension/acme_hello/.
Creating the controller
There is no console command. Create the file catalog/controller/information/hello.php by hand:
// catalog/controller/information/hello.php
namespace Opencart\Catalog\Controller\Information;
class Hello extends \Opencart\System\Engine\Controller
{
public function index(): void
{
$this->response->setOutput('Hello!');
}
}Open http://shop.test/index.php?route=information/hello — the browser shows the word «Hello!» on an empty page. In the real file the first line is the <?php tag.
How the route maps to the file
The route parameter is the path to the file inside catalog/controller/, without the .php extension:
| Address | File | Method |
|---|---|---|
index.php?route=information/hello | catalog/controller/information/hello.php | index() |
index.php?route=product/product | catalog/controller/product/product.php | index() |
index.php?route=checkout/cart | catalog/controller/checkout/cart.php | index() |
If the address names no method, index() is called.
Naming rules
| What | Rule | Example |
|---|---|---|
| Namespace | Opencart\Catalog\Controller\ plus the folder | Opencart\Catalog\Controller\Information |
| Class | File name with a capital letter | hello.php → Hello |
| File with an underscore | Each word capitalised, no underscore | review_list.php → ReviewList |
In the admin panel the namespace starts with Opencart\Admin\Controller\.
A page with the shop design
The header and the footer of the shop are controllers too. They are called with $this->load->controller(), which returns ready HTML:
public function index(): void
{
$header = $this->load->controller('common/header');
$footer = $this->load->controller('common/footer');
$this->response->setOutput($header . '<div class="container"><h1>Hello!</h1></div>' . $footer);
}The same address now shows the heading between the shop menu and the footer. HTML inside PHP is only for this first example: the templates lesson moves it into a Twig file.
Common mistake
The controller prints with echo or stops with exit. The page then arrives without headers and compression, and the output order breaks. All output goes through $this->response->setOutput() — the engine sends it at the end of the request.