The Context is a registry for PHP variables that were previously accessed as globals. It aims to standardize the way these variables are accessed, and to make the code more robust by getting rid of global vars.
These objects are always accessible through the context:
These objects are only accessible for the customer Context:
These objects are only accessible for the administrator Context:
From inside a Controller
subclass, an AdminTab
subclass or a Module
subclass, the Context should be called with this shortcut: $this->context
.
From anywhere else, you can get the Context instance by calling Context::getContext()
.
The context is initialized with data coming from the cookie or from the database. For example, to create the Language
object, the context looks for an id_lang
value in the cookie. If it doesn't find one, it will retrieve the default language id
from the database.
Whenever you would have accessed the cookie to retrieve a variable, or used a global statement, you will probably want to access the Context instead.
A few common replacements:
FrontController
subclasses are deprecated:
$id_cart = self::cart->id; |
$id_cart = $this->context->cart->id; |
$language = new Language($cookie->id_lang); $iso_code = $language->iso_code; |
$iso_code = $this->context->language->iso_code; |
More examples of Context use:
Old way |
New way |
---|---|
$cookie->id_lang; |
$this->context->language->id; |
if ($cookie->isLogged()) |
if ($this->context->customer->isLogged()) |
if ($cookie->isLoggedBack()) |
if ($this->context->employee->isLoggedBack(); |
$cart->getProducts(); |
$this->context->cart->getProducts(); |
$language = new Language($cookie->id_lang); |
$this->context->language->iso_code; |
new Currency($cookie->id_lang); |
$this->context->currency; |
$defaultCountry->id_zone; |
$this->context->country->id_zone; |
new Link(); |
$this->context->link; |
$smarty->assign(...); |
$this->context->smarty->assign(...); |