Child pages
  • Using the Context Object

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Table of contents

Table of Contents

Using the Context Object

What is the Context object?

The Context is a technical feature introduced with version 1.5 of PrestaShop. Its two goals are:

  • preventing developers from using global variables.
  • enabling them to change the context of some methods.

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.
It is a light implementation of the Registry design pattern: it is a class that stores the main PrestaShop information, such as the current cookie, the customer, the employee, the cart, Smarty, etc.

Before version 1.5, you had to rely on the cookie in order to access this data:

Code Block
languagephp
titlePrestaShop 1.4 code
$cookie->id_lang;

Now that the Context is available, the same data can be accessed more cleanly:

Code Block
languagephp
titlePrestaShop 1.5 cpde
$this->context->language->id;

What is stored by the Context?

...

A few common replacements:

  • Static shortcuts in FrontControllersubclasses are deprecated:

    Code Block
    
    $id_cart = self::cart->id;
    

    ...is to be replaced with...

    Code Block
    
    $id_cart = $this->context->cart->id;
    
  • Do not recreate an object that already exists:

    Code Block
    
    $language = new Language($cookie->id_lang);
    
    $iso_code = $language->iso_code;
    

    ...is to be replaced with...

    Code Block
    
    $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);
$language->iso_code;

$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(...);