Configuration
Since version 2.1.0 the Shopgate Library offers a revised version of the ShopgateConfig class with better support for expandability of modules. You can influence the configuration saving and loading behaviour as well as additional settings by deriving your own configuration class, for instance, in order to implement saving the configuration to a database. Better like to start coding immediately? Simply download the sample code and get going! You’re welcome to check back here anytime.
Attribute, Getter & Setter
Configuration settings are saved in class attributes. Access is performed via getter and setter methods. The following conventions apply:
- Class attributes are protected. Do not use private!
- An attribute name consists of lowercase letters and underscores. Example: $enable_mobile_redirect
Names of the getter and setter methods for an attribute must be written in CamelCase. Example:
setEnableMobileRedirect($value)
,getEnableMobileRedirect()
- Attributes representing a configuration setting are initialized in the
startup()
method.
Loading & Initializing
The following sequence is executed internally when the configuration is initialized:
- Initialization of all attributes in the class ShopgateConfig.
- The
startup()
method is called to initialize subclasses. - Loading of the passed array or the file
.../shopgate_library/config/myconfig.php
If you want to implement your own method to load configuration values (e.g. loadDatabase()
), you should call them in the startup()
method. To keep the class from trying to initialize configuration from a file or through an array, return boolean true.
In order to load the configuration after the initialization, you can call the loadArray()
or loadFile()
methods at
any time later. Their visibility is public.
Saving
The configuration can be saved to a file with the saveFile()
method. When doing that, keep in mind:
- Parameter 1 has to contain the list of fields to be saved. If no list is given, nothing will be saved.
- Parameter 2 contains the path to the file in which the configuration should be saved. If this parameter is null the class will try to
use the
.../shopgate_library/config/myconfig.php
file to save the configuration… - Parameter 3 indicates whether the saved data should (true) or should not (false) be validated.
- The method can throw a
ShopgateLibraryException
when saving or validation fails. You have to catch it.
You can implement your own method (e.g. saveDatabase()
) if you do not want to save the configuration into a file. Your method
should also throw a ShopgateLibraryException
when errors occur during the saving process, so that they can be logged and
displayed to the online shop user.
Validating
For manual validation call the validate() method. You can use the $fieldList parameter with it. If the method does not return anything, the
validation is successful. If the validation fails, it throws a ShopgateLibraryException
.
Validation rules for the ShopgateConfig class configuration are contained in the $coreValidations
attribute as regular
expressions.
There are two ways to validate additional fields of your own configuration class:
- Define your own regular expressions in the
$customValidations
attribute. - Implement the
validateCustom()
method.
Check the structure of the $coreValidations
attribute to learn what the $coreValidations
attribute has to look
like. If regular expressions are insufficient for your purposes, you can define your own logic in validateCustom()
. This method
will be called automatically. Your return value must return a list of fields for which the validation failed or an empty array for a
successful validation.
Both approaches can be combined.
Examples
The following examples are divided by chapters, but always relate to the same sample class called ShopgateConfigMyShoppingSystem. You can download the complete sample code here.
Attribute, Getter & Setter
The sample class in the listing below creates additional configuration settings and introduces a database connection stored in the $db attribute. The connection will be used in the subsequent examples.
<?
require_once(dirname(__FILE__).'/shopgate_library/shopgate.php');
class ShopgateConfigMyShoppingSystem extends ShopgateConfig {
/**
* @var DBConnector
*/
protected $db;
// additional settings
protected $country;
protected $language;
protected $currency;
protected $tax_zone_id;
protected $customer_group_id;
public function getCountry() { return $this->country; }
public function getLanguage() { return $this->language; }
public function getCurrency() { return $this->currency; }
public function getCustomerGroupId() { return $this->customer_group_id; }
public function setCountry($value) { $this->country = $value; }
public function setLanguage($value) { $this->language = $value; }
public function setCurrency($value) { $this->currency = $value; }
public function setCustomerGroupId($value) { $this->customer_group_id = $value; }
}
Initializing
The startup()
method in the following listing is an example to illustrate:
- Adding regular expressions for validation.
- Overwriting standard settings of the ShopgateConfig class.
- Initialization of the standard values for new settings.
- Loading the configuration through a custom method.
- Prevent further initialization of the ShopgateConfig class’ default routines by returning true.
<?
public function startup() {
// custom validation rules:
$this->customValidations = array(
'country' => '/[A-Z]{2}/', // 2 characters, only uppercase letters
'language' => '/[a-z]{2}/', // 2 characters, only lowercase letters
);
// overwrite some default library settings
$this->plugin_name = 'My Shopping System';
$this->enable_redirect_keyword_update = 1;
$this->enable_ping = 1;
$this->enable_add_order = 1;
$this->enable_update_order = 1;
$this->enable_get_orders = 0;
$this->enable_get_customer = 1;
/* ... */
$this->encoding = 'ISO-8859-15';
// initialize own settings
$this->country = 'US';
$this->language = 'en';
$this->currency = 'USD';
$this->customer_group_id = 2;
// load configuration from the database
try {
$this->loadDatabase();
} catch (ShopgateLibraryException $e) {
// do not interrupt the initialization, errors will be logged automatically
}
// prevent the default initialization routine to be executed
return true;
}
Loading
The loadDatabase()
method in the listing below is an example to illustrate:
- Initialization of the database connection (method initDatabase()).
- Loading the configuration from the database as a JSON string.
- Initialization with the values from the decoded JSON array.
- Appropriate error handling.
The ShopgateLibraryException
always needs to be caught in the front-end of the online shop when this
method is called.
<?
/**
* Initializes the database connection if not done yet.
*
* @throws Exception in case an error occurs.
*/
protected function initDatabase() {
if (empty($this->db)) {
$this->db = new DBConnector();
$this->db->connect();
}
}
/**
* Loads the configuration from the database.
*
* @throws ShopgateLibraryException in case an error occurs.
*/
public function loadDatabase() {
try {
$this->initDatabase();
$config = $this->jsonDecode($this->db->loadConfig('shopgate'), true);
$this->loadArray($config);
} catch (Exception $e) {
throw new ShopgateLibraryException(ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, $e->getMessage());
}
}
Saving
The saveDatabase()
method in the listing below is an example to illustrate:
- Validation of the configuration values to be saved.
- Initialization of the database connection (method initDatabase()).
- Conversion of the configuration into an array with toArray() and encoding it in JSON notation.
- Saving the created JSON string into the database.
- Appropriate error handling.
The ShopgateLibraryException
always needs to be caught in the front-end of the online shop when this
method is called.
<?
/**
* Initializes the database connection if not done yet.
*
* @throws Exception in case an error occurs.
*/
protected function initDatabase() {
if (empty($this->db)) {
$this->db = new DBConnector();
$this->db->connect();
}
}
/**
* Saves the configuration into the database as a JSON string.
*
* @param string[] $fieldList The list of fields to be saved.
* @param bool $validate True to validate the fields to be saved.
* @throws ShopgateLibraryException in case of failed validation or when an error occurred while saving.
*/
public function saveDatabase($fieldList, $validate = true) {
if ($validate) {
$this->validate($fieldList);
}
try {
$this->initDatabase();
$config = $this->jsonEncode($this->toArray());
$this->db->saveConfig('shopgate', $config);
} catch (Exception $e) {
throw new ShopgateLibraryException(ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, $e->getMessage());
}
}
Validating
Regular expressions contained in the $customValidations
attribute will automatically be applied when the validate()
method gets called. The following method can be used for validations that cannot be covered by regular expressions, or when you want to
avoid using regular expressions.
The validateCustom()
method in the following listing is an example to illustrate:
- Going through the list of fields to be validated.
- A sample validation of the
$currency
and$customer_group_id
settings. - Returning names of the fields that failed validation or an empty array if validation was okay.
This method is automatically called with the validate()
method. There is no need to call it separately.
<?
protected function validateCustom(array $fieldList = array()) {
$failedFields = array();
foreach ($fieldList as $fieldName) {
switch ($fieldName) {
case 'currency': // must be one of "EUR", "USD" or "GBP"
if (!in_array($this->$fieldName, array('EUR', 'USD', 'GBP'))) {
$failedFields[] = $fieldName;
}
break;
case 'customer_group_id': // must be numeric
if (!is_numeric($this->fieldName)) {
$failedFields[] = $fieldName;
}
break;
}
}
return $failedFields;
}