Internal objects


1Overview

When Temma executes a request, it instantiates several objects that are necessary for this processing, and makes them available to controllers and plugins.

These objects are of type:

  • \Temma\Base\Session: user session management (see dedicated documentation).
  • \Temma\Web\Config: configuration information retrieval.
  • \Temma\Web\Request: retrieve and modify data making up the request.
  • \Temma\Web\Response: control of certain response parameters.

2Config

2.1Config : overview

This object is used to access and modify the site's configuration at the time of the current request.

The configuration object is available in controllers and plugins by writing:

$this->_config

In other objects managed by the dependency injection component, the configuration object is accessible by writing:

$this->_loader->config

2.2Config: read-write attributes

  • appPath : (string) path to the project's root
  • etcPath : (string) path to the project's 'etc' directory
  • logPath : (string) path to the project's 'log' directory
  • tmpPath : (string) path to the project's 'tmp' directory
  • includesPath : (string) path to the project's 'lib' directory
  • controllersPath : (string) path to the project's 'controllers' directory
  • varPath : (string) path to the project's 'var' directory
  • webPath : (string) path to the project's 'www' directory
  • routes : (array) basic routing
  • plugins : (array) list of plugins
  • enableSessions : (bool) indicates whether sessions are enabled
  • rootController : (string) name of the root controller
  • defaultController : (string) name of the default controller
  • proxyController : (string) name of the proxy controller
  • defaultNamespace : (string) default controller namespace
  • defaultView : (string) name of the default view
  • loader : (string) name of the object used as dependency injection component
  • loaderAliases : (?array) associative array containing naming aliases managed by the loader
  • loaderPrefixes : (?array) associative array containing naming prefixes managed by the loader
  • logManager : (null|string|array) name of the name manager(s)
  • logLevels : (null|string|array) log thresholds
  • bufferingLoglevels : (null|string|array) buffered log thresholds

2.3Config: management of extended configurations

The xtra() method is used to read an extended configuration:

// retrieve the entire “x-user” extended configuration
$conf = $this->_config->xtra('user');

// retrieve the “login” key
$login = $this->_config->xtra('user', 'login');

// retrieve “login” key, with default value
$login = $this->_config->xtra('user', 'login', 'admin');

The setXtra() method is used to define a key in an extended configuration:

// set the “login” key in the “x-user” extended configuration
$this->_config->setXtra('user', 'login', 'sysop');

3Request

3.1Request: overview

Request management is rarely used in application controllers. However, it can be useful in plugins that want to control the execution flow by changing the characteristics of the request.

The request object is available in controllers and plugins by writing:

$this->_request

In other objects managed by the dependency injection icomponent, the request object is accessible by writing:

$this->_loader->request

3.2Request: reading methods

// find out if it's an AJAX request
$ajax = $this->_request->isAjax();

// retrieve the data formats accepted by the browser
// ("text/html", "application/json", "image/png", etc.)
$formats = $this->_request->getAcceptedFormats();

// indicates whether a given format is accepted by the browser
// ("text/html", "text", "image/png", "image", "*/*", "*", etc.)
$bool = $this->_request->isAcceptedFormat($format);

// retrieve path info
$pathInfo = $this->_request->getPathInfo();

// retrieve method (GET, POST...)
$method = $this->_request->getMethod();

// retrieve controller name
$ctrl = $this->_request->getController();

// retrieve action name
$action = $this->_request->getAction();

// retrieve number of parameters
$cnt = $this->_request->getParamCount();

// retrieve list of parameters
$params = $this->_request->getParams();

// retrieve the first parameter
$p1 = $this->_request->getParam(0);
// retrieve the 2nd parameter, with a default value
$p2 = $this->_request->getParam(1, 'toto');

// retrieve path from site root
$path = $this->_request->getSitePath();

3.3Request: writing methods

// method definition
$this->_request->setMethod('POST');

// controller definition
$this->_request->setController('user');
// recommended: update associated template variable
$this['CONTROlLER'] = 'user';

// action definition
$this->_request->setAction('list');
// recommended: update associated template variable
$this['ACTION'] = 'list';

// define parameter list
$this->_request->setParams(['toto', 'titi']);

// define the second parameter
$this->_request->setParam(1, 'tata');

3.4Request: validation methods

The Request object provides four methods to validate incoming data : validateParams(), validateInput(), validatePayload() and validateFiles().

Validations are based on contracts in the format expected by the DataFilter object.

These methods throw a \Temma\Exceptions\Application exception if the data is invalid. They throw a \Temma\Exceptions\IO exception if a contract is incorrect.

validateParams()

This method validates parameters received in the URL.

In non-strict validation mode (default behavior), parameters may be modified : a string exceeding the defined maximum length will be truncated, types are converted if necessary, undefined parameters are removed, etc.

Parameters:

  • $contract (null|string|array) : Validation contract definition. It can be one of two types :
    • A string corresponding to a validation contract defined in the configuration file, or to a validation object.
    • A list of contracts (see the DataFilter object), with one contract per parameter. It is possible to specify ... to indicate that the following parameters are accepted as-is.
  • $strict (bool) : Enables strict validation mode (see the DataFilter object).
  • &$output (mixed) : Reference variable that will receive the DataFilter output data (validated/filtered data and optional metadata).

If more parameters are provided than defined, and there is no ... entry in the contract list :

  • In non-strict mode, additional parameters are removed.
  • In strict mode, an exception is thrown.

Examples :

// validates that the first parameter is an integer greater than or equal to 20
// and that the second is a hexadecimal color
$request->validateParams(['int; min: 20', 'color']);

// validates that the first parameter is a positive integer,
// the second is an enumeration, and the third is a string
// starting with "foo"
$request->validateParams([
    'int; min: 0',
    'enum; values: member, admin',
    'string; mask: ^foo'
]);

// validates that the first parameter is an integer
// and that additional parameters are allowed
$request->validateParams(['int', '...']);

// validates a contract named "userUpdateParams" defined in configuration,
// and declared as follows:
// 'validationTypes' => [
//     'userUpdateParams' => 'list; values: int, int, string'
// ]
$request->validateInput('userUpdateParams');

// validate and retrieve filtered data
$output = null;
$request->validateParams(['int; min: 1', 'slug'], output: $output);
// $output contains the validated parameters
validateInput()

This method validates data received as GET or POST parameters.

In non-strict validation mode (default behavior), GET/POST parameters may be modified: a string exceeding the defined maximum length will be truncated, types are converted if necessary, undefined parameters are removed, etc.

Parameters:

  • $contract (null|string|array) : Validation contract definition. It can be one of two types :
    • A string corresponding to a validation contract defined in the configuration file, or to a validation object.
    • Associative array whose keys are GET/POST parameters and whose values are validation contracts (see the DataFilter object) for each parameter. Using the ... key makes it possible to accept undefined parameters, optionally enforcing their type.
  • $source (?string) : Parameter source ('GET' or 'POST'). By default, validation operates on both GET and POST data (checking for the presence of GET and/or POST data).
  • $strict (bool) : Enables strict validation mode (see the DataFilter object).
  • &$output (mixed) : Reference variable that will receive the DataFilter output data (validated/filtered data and optional metadata).

Examples:

// expects parameters 'lastname' and 'firstname'
$request->validateInput(['lastname', 'firstname']);

// expects POST parameters 'id' (integer greater than or equal to 100)
// and 'mail' (email ending with "@test.com")
$request->validateInput(
    [
        'id'   => 'int; min: 100',
        'mail' => 'email; mask: @test.com$',
    ],
    'POST'
);

// accepts all parameters, as long as they can be converted to integers
$request->validateInput(['...' => 'int']);

// strictly validates GET parameters 'lastname' (required)
// and 'firstname' (optional), and non-strictly validates parameter 'age' (required)
$request->validateInput(
    [
        'lastname'   => 'string',
        'firstname?' => 'string',
        'age'        => '~int',
    ],
    'GET',
    true
);

// validates a contract named "user" defined in configuration,
// and declared as follows:
// 'validationTypes' => [
//     'user' => [
//         'id?'       => 'int',
//         'lastname'  => 'string',
//         'firstname' => 'string',
//         'age'       => '~int',
//     ]
// ]
$request->validateInput('user');

// validate POST parameters and retrieve filtered data
$output = null;
$request->validateInput(
    ['name' => 'string', 'email' => 'email'],
    'POST',
    output: $output
);
// $output contains the validated/filtered POST data
validatePayload()

This method validates data sent in the request body (the "payload").

Parameters :

  • $contract (null|string|array) : Validation contract definition. It can be one of two types :
    • A string corresponding to a validation contract defined in the configuration file, or to a validation object.
    • A validation contract (see the DataFilter object).
  • $strict (bool) : Enables strict validation mode (see the DataFilter object).
  • &$output (mixed) : Reference variable that will receive the DataFilter output data (validated/filtered data and optional metadata).

Examples:

// validates a JSON stream containing a list of integers
$request->validatePayload([
    'type'     => 'json',
    'contract' => 'list; contract: int'
]);

// validates a JSON stream containing an associative array
$request->validatePayload([
    'type'     => 'json',
    'contract' => [
        'type' => 'assoc',
        'keys' => [
            'id'       => 'int',
            'lastname' => 'string; minLen: 2',
            'birthday' => 'date; format: Y-m-d',
            'role'     => 'enum; values: user, member, admin',
            'labels?'  => 'list; contract: string',
        ]
    ]
]);

// validates a base64-encoded GIF or PNG image
$request->validatePayload('base64; mime: image/gif, image/png');

// validates a binary stream containing a PDF or an image
$request->validatePayload('binary; mime: application/pdf, image');

// validates a contract named "avatar" defined in configuration,
// and declared as follows:
// 'validationTypes' => [
//     'avatar' => 'base64; mime: image; maxLen: 1M'
// ]
$request->validatePayload('avatar');

// validate a binary stream and retrieve metadata
$output = null;
$request->validatePayload('binary; mime: image', output: $output);
// $output contains ['binary' => ..., 'mime' => ..., 'charset' => ...]
validateFiles()

This method validates uploaded files.

Parameters :

  • $contracts (array) : Associative array whose keys are file names, and whose values are validation contracts (see the DataFilter object) for each file.
  • $strict (bool) : Enables strict validation mode (see the DataFilter object).

Examples :

// validates a required JSON file named "definition"
// and an optional image named "avatar"
$request->validateFiles([
    'definition' => 'json',
    'avatar?'    => 'binary; mime: image',
]);

// validates a JSON stream containing an integer, and any number of PDF files
$request->validateFiles([
    'count' => 'json; contract: int',
    '...'    => 'binary; mime: application/pdf',
]);

4Response

4.1Response: overview

This object is used to retrieve and manipulate the information used to generate the response sent by Temma to the browser.

The response object is available in controllers and plugins by writing:

$this->_response

In other objects managed by the dependency injection component, the response object is accessible by writing:

$this->_loader->response

4.2Response: reading methods

// retrieve redirection URL (or null)
$url = $this->_response->getRedirection();

// retrieve redirection code (301 or 302)
$code = $this->_response->getRedirectionCode();

// retrieve HTTP error code (or null)
$httpError = $this->_response->getHttpError();

// retrieve HTTP return code
$httpCode = $this->_response->getHttpCode();

// retrieve name of defined view
$view = $this->_response->getView();

// retrieve template prefix
$prefix = $this->_response->getTemplatePrefix();

// retrieve defined template (or null)
$tpl = $this->_response->getTemplate();

// retrieve list of HTTP headers
$headers = $this->_response->getHeaders();

// retrieve all defined template variables
$vars = $this->_response->getData();
// retrieve a template variable
$var = $this->_response->getData('var');
// retrieve a template variable with a default value
// (if default value is used, it is added to template variables)
$var = $this->_response->getData('var', 'default');
// retrieve a template variable, using an anonymous function
// to define the default value
$var = $this->_response->getData('var', function() {
    return 'default';
});
// same as above, but providing a parameter to the anonymous function
$var = $this->_response->getData('var', function($param) {
    return $param * 2;
}, $autreValeur);

4.3Response: writing methods

// define a temporary redirection (code 302)
$this->_response->setRedirection($url);
// set permanent redirection (code 301)
$this->_response->setRedirection($url, true);
// redirect to HTTP referer, with fallback to $url (code 302)
$this->_response->setRedirection($url, false, true);
// 301 redirect to HTTP referer, with fallback to $url
$this->_response->setRedirection($url, true, true);

// set HTTP error code
$this->_response->setHttpError(500);

// set HTTP return code
$this->_response->setHttpCode(404);

// set view name
$this->_response->setView('\Temma\Views\Json');
$this->_response->setView('~Json');
// disable view processing
$this->_response->setView(false);

// add a template variable
$this->_response['key'] = 'value';
// delete a template variable
unset($this->_response['key']);
// redefine all template variables
$this->_response->setData([
    'key1' => 'value1',
    'key2' => 'value2',
]);
// add multiple template variables
$this->_response->addData([
    'key3' => 'value3',
    'key4' => 'value4',
]);
// delete all template variables
$this->_response->clearData();

// set template prefix
$this->_response->setTemplatePrefix($prefix);

// set template path
$this->_response->setTemplate('article/voir.tpl');

// add HTTP header
$this->_response->header('Content-Type: application/pdf');

4.4Response: validation methods

The Response object provides two methods to manage an output data validation contract, which can be used by the view to validate data before sending it to the browser.

Validations are based on contracts in the format expected by the DataFilter object.

setValidationContract()

This method sets the validation contract for output data.

Parameters:

  • $contract (null|string|array) : Validation contract definition. It can be one of three types :
    • null to remove the validation contract.
    • A string corresponding to a validation contract defined in the configuration file, or to a validation object.
    • A validation contract (see the DataFilter object).

Examples:

// set a named contract defined in configuration
$this->_response->setValidationContract('contractName');

// set a contract as an array
$this->_response->setValidationContract([
    'key1' => 'int',
    'key2' => 'string; minLen: 2',
]);

// remove the validation contract
$this->_response->setValidationContract(null);
getValidationContract()

This method returns the defined validation contract, or null if no contract has been set.

Example:

// retrieve the output data validation contract
$contract = $this->_response->getValidationContract();