ZnetDK 4 Mobile

ZnetDK PHP API

Server-side Application PHP Methods

The ZnetDK PHP API simplifies the development on the web server side of:

  • the views implemented to display data,
  • the navigation menu items and icons,
  • the controller actions generally called in AJAX by the views of the application,
  • the validation of data transmitted by the view
  • and the access to the MySQL database in read or write.

Its source code is defined through PHP classes located in the INSTALL_DIR/engine/core/ folder.

Application views

Application views are PHP scripts that are developed to display data and input forms dedicated to the end user.
They are written in pure HTML and include if necessary, PHP and JavaScript code.
A view is usually displayed when you click an item of the navigation menu.

Once a view is displayed, it remains in the DOM (Document Object Model) of the page, even when another one is displayed as a replacement.
This means that the view is not reloaded when it is displayed again later.
To force the content of the view to refresh each time it is displayed again, simply add the zdk-viewreload CSS class to any HTML element in the view.

The PHP script of a view, for example myview.php, is installed into the INSTALL_DIR/applications/default/app/view/ folder.

EXAMPLE: myview.php
<h3>My view</h3>
<p class="zdk-viewreload">The name of the application is <?php echo LC_HEAD_TITLE; ?></p>
<p>The current time is <span id="current-time"></span>
<script>
    var currentTime = new Date();
    $('#current-time').text(currentdate.getHours()
        + ':' + currentdate.getMinutes());
</script>

A view can be translated and displayed into multiple languages if the application is configured for multi-language display.

Navigation menu

The basics

The Web app navigation menu is defined in PHP on the server side of the application.
Its definition is centralized into the INSTALL_DIR/applications/default/app/menu.php script through the \app\Menu class.
The \app\Menu::initAppMenuItems() method is called by ZnetDK to retrieve the menu items to display in the horizontal and vertical menus.
Each menu item is added to the navigation menu by calling the \MenuManager::addMenuItem() static method.

Here is below the definition of the Starter App navigation menu.

The Starter App's menu.php script

<?php
/**
 * ZnetDK, Starter Web Application for rapid & easy development
 * See official website http://www.znetdk.fr
 * ------------------------------------------------------------
 * Custom navigation menu of the application
 * YOU CAN FREELY CUSTOMIZE THE CONTENT OF THIS FILE
 */
namespace app;
class 
Menu implements \iMenu {

    static public function 
initAppMenuItems() {
        \
MenuManager::addMenuItem(NULL'home''Home''fa-home');

        \
MenuManager::addMenuItem(NULL'_authorizations'LC_MENU_AUTHORIZATION'fa-unlock-alt');
        \
MenuManager::addMenuItem('_authorizations''z4musers'LC_MENU_AUTHORIZ_USERS'fa-user');
        \
MenuManager::addMenuItem('_authorizations''z4mprofiles'LC_MENU_AUTHORIZ_PROFILES'fa-key');
    }

}

The first call to \MenuManager::addMenuItem() adds the Home menu item in first position. This is a one level menu item so the Home label is both displayed on the main vertical menu and the secondary horizontal menu.

The three next calls to \MenuManager::addMenuItem() add the Authorizations menu item on the main vertical menu. This is a two levels menu item with two subitems named Users and Profiles displayed on the secondary horizontal menu.

Class \MenuManager

 Method addMenuItem()

DESCRIPTION Add a menu item to the navigation menu. This method is called from the class app\Menu of the application.
PARAMETERS
$parentMenuItemID String | NULL Parent menu item ID, NULL for root item.
$menuItemID String Menu item ID of the item to add. This ID matches the name of the PHP view script (without .php file extension) if the menu item is not the level one menu item of a two levels menu definition.
$menuItemLabel String Menu item label of the item to add.
$menuItemIcon String Font Awesome 4 style class of the icon to display for the menu item.
$menuItemSEOlink String OPTIONAL, SEO link for the menu item (only used if CFG_VIEW_PAGE_RELOAD is set to TRUE).
$menuItemDescription String OPTIONAL, Text for the HTML meta tag description (only used if CFG_VIEW_PAGE_RELOAD is set to TRUE).
$menuItemKeywords String OPTIONAL, Text for the HTML meta tag keywords (only used if CFG_VIEW_PAGE_RELOAD is set to TRUE).
$menuItemAuthor String OPTIONAL, Text for the HTML meta tag author (only used if CFG_VIEW_PAGE_RELOAD is set to TRUE).

EXAMPLE
<?php
// The 'my_view.php' view is displayed on clicking on the "My view" menu item.
// The Font Awesome 4 'fa-book' icon is displayed for this menu item.
\MenuManager::addMenuItem(NULL'my_view''My view''fa-book');

Application controller

An application controller is a PHP class derived from the ZnetDK \AppController class that performs actions in response to AJAX requests sent by a view of the application.
A controller action is a protected method of the controller class whose name is prefixed by the action_ string.
The POST parameters sent by the view in AJAX are read thanks to a \Request object.
The response is returned to the calling view in JSON format through a \Response object.

Here is an example below of the mycontroller.php PHP script implementing the MyController class having a myaction action.

EXAMPLE
<?php
namespace app\controller;
class 
MyController extends \AppController {

    static protected function 
action_myaction() {
        
$request = new \Request();
        
$postValue $request->my_param;
        
$response = new \Response();
        
$response->my_response $postValue;
        return 
$response;
    }
}
?>

This controller action reads the value of the my_param POST parameter and returns a JSON object with a property named my_response and a value matching the my_param parameter value.

You can notice in this example that the namespace is set to app\controller. It matches the folder in which the mycontroller.php script file must be located, i.e. in the INSTALL_DIR/applications/default/app/controller/ folder if the running application is the Starter Application (default subfolder).

Class \AppController

Any application controller class must derive from the abstract \AppController class.

 Method doAction()

DESCRIPTION Executes the action specified in parameter.
PARAMETERS
$action String Name of the action without the action_ prefix of the class method (for example 'store' that corresponds to the action_store() method of the controller class).
RETURNED VALUE \Response The response returned by the controller's action as a \Response object.
EXAMPLE
<?php
$response 
= \app\controller\MyCtrl::doAction('getall');

Class \Request

The class \Request when instantiated in a controller action, is used to read the values of the POST parameters sent through an AJAX request from an app view.

 Property $[postParameterName]

DESCRIPTION Value of the POST parameter named [postParameterName] which was transmitted by the HTTP request.
ACCESS Public
DATATYPE String
DEFAULT VALUE NULL
EXAMPLE
<?php
$request 
= new \Request();
/* The read POST parameter is named "address" */
$requestedAddress $request->address;

 Method getValuesAsMap()

DESCRIPTION Returns the POST parameters whose names are given as parameters in the form of an associative array, where each key corresponds to the name of the POST parameter.
PARAMETERS
$postParameter1 String Name of the first POST parameter.
$postParameter2 String Name of the second POST parameter.
$postParameterN String Name of the Nth POST parameter.
RETURNED VALUE Array Associative array of values whose POST parameters have been given as parameters.
EXAMPLE
<?php
$request 
= new \Request();
$postValues $request->getValuesAsMap('lastname','firstname');
// For example, the returned associative array is ['lastname' => 'DOE','firstname' => 'John']

Class \Response

A controller action always returns an object of type \Response in response to the original HTTP request.
The returned object takes one of the following formats, depending on the case:


 Property $[propertyName]

DESCRIPTION Property named [propertyName] of the JSON object returned by a controller action in response to a HTTP POST request.
ACCESS Public
DATATYPE Mixed
DEFAULT VALUE NULL
EXAMPLE
<?php
$response 
= new \Response();
$response->myFirstValue 'value 1';
$response->myOtherValue 124.59;

 Method setResponse()

DESCRIPTION Set the response of the controller action from an array.
The array is converted to a JSON object before beeing returned in response of the HTTP POST request.
PARAMETERS
$responseData Array Data to return in JSON by the controller action
EXAMPLE
<?php
$response 
= new \Response();
$response->setResponse([
    
'status' => 'KO',
    
'message' => 'An error occurred!'
]);

 Method setFileToDownload()

DESCRIPTION Specifies the file to return in the HTTP GET response for download.
This method must only be called from the action_download() method of an application controller.
PARAMETERS
$filePath String File path of the file to download. The CFG_DOCUMENTS_DIR constant can be used to get the web server side storage path of the file to download.
$forDisplayInline Boolean OPTIONAL, if set to TRUE, the file is downloaded with the content-disposition attribute set to inline in the HTTP response header.
$downloadedFilename String OPTIONAL, name of the downloaded file. If not set, the name specified for the $filepath parameter is used instead.
EXAMPLE
<?php
static protected function action_download() {
    
$response = new \Response();
    
$fileToDownload CFG_DOCUMENTS_DIR DIRECTORY_SEPARATOR 'mydoc.pdf';
    
$response->setFileToDownload($fileToDownloadTRUE);
    return 
$response;
}

 Method setView()

DESCRIPTION Specifies the name of the view and its type to return in the HTTP GET response.
PARAMETERS
$viewName String Name of the view to render.
$viewType String Type of view to render ('view' or 'help').
$viewCaller mixed OPTIONAL, caller of this method or data given to the view.
This value can be read within the called view through the $this->viewCaller property. So, the called view can adapt the content to be rendered according to this property value.
EXAMPLE
<?php
$response 
= new \Response();
/* Returns the view "applications\default\app\view\customers.php" */
$response->setView('customers','view');

 Method setDataForCsv()

DESCRIPTION Sets the data of the CSV file to be returned in the HTTP GET response for download.
This method must only be called from the action_download() method of an application controller.
The LC_LOCALE_CSV_SEPARATOR parameter of the application's translation script INSTALL_DIR/applications/default/app/lang indicates which character separates the values of the CSV file to generate (comma or semicolon separator).
PARAMETERS
$rowData Array 2-dimensional array containing the data rows of the CSV file.
$filename String Name given to the CSV file requested for download
$header array OPTIONAL, array which contains the column header labels of the CSV file.
$forDisplayInline Boolean OPTIONAL, set to FALSE by default, specifies whether the file should be viewed or saved to disk after downloading.
If the value is TRUE, the downloaded file is intended to be displayed directly in the internet browser (Content-Disposition: inline header).
EXAMPLE
<?php
static protected function action_download() {
    
$response = new \Response();
    
$header = array('Column 1','Column 2','Column 3');
    
$data = array(
        array(
'Row 1 col. 1','Row 1 col. 2','Row 1 col. 3'),
        array(
'Row 2 col. 1','Row 2 col. 2','Row 2 col. 3'),
        array(
'Row 3 col. 1','Row 3 col. 2','Row 3 col. 3'),
    );
    
$response->setDataForCsv($data'myfile.csv'$header);
    return 
$response;
}

 Method setPrinting()

DESCRIPTION Defines an object of type FPDF as a response to the HTTP GET request.
This method must only be called from the action_download() method of an application controller.
PARAMETERS
$printingObject FPDF FPDF object to output.
$filename String OPTIONAL, name given to the PDF file requested for download (named doc.pdf by default).
EXAMPLE
<?php
static protected function action_download() {
    
$response = new \Response();
    
$pdf = new \FPDF();
    
$pdf->AddPage();
    
$pdf->SetFont('Arial','B',16);
    
$pdf->Cell(40,10,'PDF document generated from ZnetDK!');
    
$response->setPrinting($pdf'mydoc.pdf');
    return 
$response;
}

 Method setSuccessMessage()

DESCRIPTION Initializes the message to be returned in JSON format to the user in the HTTP POST response, to confirm that the requested action was performed successfully.
PARAMETERS
$summary String Summary of the message
$message String Text of the message.
EXAMPLE
<?php
$response 
= new \Response();
$response->setSuccessMessage('New item','Item added successfully.');

 Method setWarningMessage()

DESCRIPTION Initializes the message to be returned in JSON format to the user in the HTTP POST response, to confirm that the requested action succeeded with warning.
PARAMETERS
$summary String Summary of the message
$message String Text of the message.
EXAMPLE
<?php
$response 
= new \Response();
$response->setWarningMessage('New item','Item added even if it was incomplete.');

 Method setFailedMessage()

DESCRIPTION Initializes the message to be returned in JSON format to the user in the HTTP POST response, to notify user that the requested action failed.
PARAMETERS
$summary String Summary of the message
$message String Text of the message.
$fieldInError String OPTIONAL, name of the data form's HTML field in error.
EXAMPLE
<?php
$response 
= new \Response();
$response->setFailedMessage('New item','Item added even if it was incomplete.');

 Method setCriticalMessage()

DESCRIPTION Initializes the message to be returned in JSON format to the user in the HTTP POST response, to notify user that the requested action failed with a critical error.
PARAMETERS
$message String Text of the message.
$exception \Exception Exception causing critical error.
EXAMPLE
<?php
try {
    
$myDao->getResult();
} catch (\
PDOException $ex) {
    
$response = new \Response();
    
$response->setCriticalMessage('Unable to store the item data'$ex);
}

Database Access

Access to the data stored into the database of the application is simplified thanks to the ZnetDK PHP classes \DAO and \SimpleDao, both based on the PHP PDO class.

Class \DAO

The ZnetDK class \DAO allows to achieve complex database operations, in particular when data is to be selected from multiple SQL tables.

This class is abstract and so requires the declaration of a derived class which implements the method initDaoProperties().
At least, the $table or $query property must be initialized from the initDaoProperties() method.
The PHP script of the derived \DAO class is located into the INSTALL_DIR/applications/default/app/model/ folder if the running application is the Starter Application (default subfolder).

See in this page properties and methods of the \DAO class.

See below an example of custom \DAO class.

EXAMPLE
<?php
namespace app\model;
class 
TaskDAO extends \DAO {

    protected function 
initDaoProperties() {
        
$this->table "zdkapp_tasks";
        
$this->query "SELECT tas.*, tas.id AS task_id, usr.user_name,
            IF(tas.status_id < 3 AND tas.end_date < CURDATE(), 1, 0) AS late,
            IF(tas.status_id < 3, 0, 1) AS display_priority
            FROM tasks AS tas
            INNER JOIN zdk_users AS usr ON usr.user_id = tas.user_id"
;
        
$this->dateColumns = array('begin_date''end_date''creation_date');
    }

    public function 
setNotFinishedAsFilter() {
        
$this->filterClause 'WHERE tas.status_id != ?';
        
$this->setFilterCriteria(3);
    }

}
?>

\DAO PROPERTIES

$table, $query, $filterClause, $groupByClause, $idColumnName, $dateColumns, $moneyColumns, $amountColumns, $tableAlias

 Property $table
DESCRIPTION Name of the SQL table to update when calling the \DAO::store() and \DAO::remove() methods.
If the \DAO::$query property is not initialized, the \DAO::getResult() method returns all the rows and columns of the specified table.
ACCESS Protected
DATATYPE String
DEFAULT VALUE undefined
EXAMPLE
<?php
$this
->table 'my_table';

 Property $query
DESCRIPTION SQL query executed to select data when the \DAO::getResult() method is called.
ACCESS Protected
DATATYPE String
DEFAULT VALUE undefined
EXAMPLE
<?php
$this
->query "SELECT col1, col2 FROM my_table";

 Property $filterClause
DESCRIPTION SQL condition applied dynamically when calling the \DAO::getResult() method to filter the rows returned.
The values of the SQL condition are set through a call to the \DAO::setFilterCriteria() method.
ACCESS Protected
DATATYPE String
DEFAULT VALUE FALSE
EXAMPLE
<?php
$this
->filterClause "WHERE col1 = ?";

 Property $groupByClause
DESCRIPTION GROUP BY clause of the SQL query.
The grouping clause must be specified outside the \DAO::$query property in the case where a custom filter is defined through the \DAO::$filterClause property.
ACCESS Protected
DATATYPE String
DEFAULT VALUE FALSE
EXAMPLE
<?php
$this
->groupByClause "GROUP BY col1 HAVING COUNT(col1) > 5";

 Property $IdColumnName
DESCRIPTION Name of the column in the SQL table corresponding to the Primary Key.
This property must be changed if the primary key column is not named id.
ACCESS Protected
DATATYPE String
DEFAULT VALUE 'id'
EXAMPLE
<?php
$this
->IdColumnName 'my_row_id';

 Property $dateColumns
DESCRIPTION Array containing the names of the DATE columns to format according to the current displayed language.
The specified date columns are returned by the \DAO::getResult() method with _locale as suffix (for example mydatecol_locale).
ACCESS Protected
DATATYPE Array
DEFAULT VALUE []
EXAMPLE
<?php
$this
->dateColumns = ['creation_date''update_date'];

 Property $moneyColumns
DESCRIPTION Array containing the names of the columns to display as money according to the current displayed language.
The specified columns are returned by the \DAO::getResult() method with _money as suffix (for example my_amount_money).
ACCESS Protected
DATATYPE Array
DEFAULT VALUE []
EXAMPLE
<?php
$this
->moneyColumns = ['subtotal''total'];

 Property $amountColumns
DESCRIPTION Array containing the names of the columns to display as amount according to the current displayed language.
The specified columns are returned by the \DAO::getResult() method with _amount as suffix (for example balance_amount).
ACCESS Protected
DATATYPE Array
DEFAULT VALUE []
EXAMPLE
<?php
$this
->amountColumns = ['subtotal''total'];

 Property $tableAlias
DESCRIPTION Alias of the SQL table.
The alias must be specified if the SQL query defined for the \DAO::$query property uses an SQL alias.
If you don't specify the alias, an error is returned by the \DAO::getById() method.
ACCESS Protected
DATATYPE String
DEFAULT VALUE FALSE
EXAMPLE
<?php
$this
->query "SELECT col1, col2 FROM my_table AS tab";
$this->tableAlias 'tab';

\DAO METHODS

initDaoProperties(), setFilterCriteria(), setSortCriteria(), setLimit(), setSelectedColumns(), setForUpdate(), getResult(), getById(), getCount(), store(), remove(), beginTransaction(), commit(), rollback()

 Method initDaoProperties()
DESCRIPTION Abstract method implemented by the derived class to initialize the properties of the \DAO object.
EXAMPLE
<?php
namespace app\model;
class 
Customers extends \DAO
{
  protected function 
initDaoProperties() {
    
$this->query "SELECT id, customer_name FROM customers";
    
$this->filterClause "WHERE customer_name LIKE ?";
  }
}

 Method setFilterCriteria()
DESCRIPTION Sets one or several values for filtering rows.
These values are passed in parameters of the method in the same order than the placeholders (i.e ?) set for the $filterClause property.
PARAMETERS
$filterValue1 mixed First value of the first filter criterium.
$filterValue2 mixed Second value of the second filter criterium.
$filterValueN mixed Nth value of the Nth filter criterium.
EXAMPLE
<?php
$customers 
= [];
$myDao = new \app\model\Customers();
$myDao->setFilterCriteria('spain','france','uk');
while(
$row $myDao->getResult()) {
    
$customers[] = $row;
}

 Method setSortCriteria()
DESCRIPTION Sets the sort criteria to apply to the rows returned by the getResult() method.
PARAMETERS
$sortCriteria String A comma-separated list of the columns involved in row sorting, just like the ORDER BY clause in SQL.
EXAMPLE
<?php
$customers 
= [];
$myDao = new \app\model\Customers();
$myDao->setSortCriteria('name DESC, city ASC');
while(
$row $myDao->getResult()) {
    
$customers[] = $row;
}

 Method setLimit()
DESCRIPTION Limits the number of rows returned by the getResult() method.
This method applies the LIMIT clause to the SQL query executed to select the rows.
PARAMETERS
$offset Integer First row number to select starting to 0.
$count Integer Number of rows to select.
EXAMPLE
<?php
$customers 
= [];
$myDao = new \app\model\Customers();
$myDao->setLimit(20,40);
while(
$row $myDao->getResult()) {
    
$customers[] = $row;
}

 Method setSelectedColumns()
DESCRIPTION Reduces the values returned when selecting rows to only specified columns.
PARAMETERS
$columns Array The columns to select.
EXAMPLE
<?php
$customers 
= [];
$myDao = new \app\model\Customers();
$myDao->setSelectedColumns(array('id','name'));
while(
$row $myDao->getResult()) {
    
$customers[] = $row;
}

 Method getResult()
DESCRIPTION Returns the current data row.
RETURNED VALUE Array | FALSE Data of the current row as an associative array where each key matches a column name of the SQL table.
Returns FALSE if no data row exists or if the last data row has already been returned at the previous call.

EXAMPLE
<?php
$customers 
= [];
$myDao = new \app\model\Customers();
while(
$row $myDao->getResult()) {
    
$customers[] = $row;
}

 Method getById()
DESCRIPTION Returns the row's data matching the specified identifier.
PARAMETERS
$id Integer Identifier of the row to select in the SQL table.
RETURNED VALUE Array | FALSE Associative array containing the data of the selected row.
Returns FALSE if no data row exists for the specified identifier.

EXAMPLE
<?php
$myDao 
= new \app\model\Customers();
$rowData $myDao->getById(43);
$customerName $rowData['customer_name'];

 Method getCount()
DESCRIPTION Returns the total number of data rows returned by the method getResult() if it is next called.
RETURNED VALUE Integer Number of data rows.
EXAMPLE
<?php
$myDao 
= new \app\model\Customers();
$rowCount $myDao->getCount();

 Method store()
DESCRIPTION Stores in the SQL table of the DAO the specified data row.
PARAMETERS
$row Array Data row as an associative array where each key corresponds to a column name in the SQL table.
If the identifier is specified in the array, the data row is updated (UPDATE in SQL).
Otherwise, the data row is inserted in the table (INSERT in SQL).
$autocommit Boolean Specifies whether the data must be commited after its update or insertion.
$emptyValuesToNull Boolean If TRUE, converts the empty values (ie '') to NULL.
RETURNED VALUE Integer Identifier of the row inserted or updated.
EXAMPLE
<?php
$row 
= array('id'=>18,'name'=>'MARTIN','city'=>'Paris');
$myDao = new \app\model\Customers();
$result $myDao->store($row);

 Method remove()
DESCRIPTION Removes the table's row matching the specified row identifier.
If the row identifier is not set in paramater, the filter criteria set for the DAO object are used to remove the corresponding rows.
PARAMETERS
$rowID Integer | NULL Identifier of the row to remove or NULL for removing multiple rows matching selection criteria.
$autocommit Boolean Specifies whether the data once removed must be commited or not.
RETURNED VALUE Integer The number of rows removed.
EXAMPLE
<?php
$customerId 
52;
$myDao = new \app\model\Customers();
$rowCount $myDao->remove($customerId);

 Method beginTransaction()
DESCRIPTION Starts an explicit SQL transaction which requires a call to commit() or rollback() to end it.
PARAMETERS
$silent Boolean OPTIONAL, set to FALSE by default. if set to TRUE, the transaction is not started if it is already active and no exception is thrown.
EXAMPLE
<?php
$myDao 
= new \app\model\Customers();
$myDao->beginTransaction();

 Method setForUpdate()
DESCRIPTION Enables or disables the locking of selected rows by adding the FOR UDATE clause to the SQL query.
A SQL transaction must first be explicity started via beginTransaction() before calling this method.
Next the rows are selected using the getResult() and getById() methods.
PARAMETERS
$isForUpdate Boolean Value TRUE for enabling rows locking, FALSE to disable it.
EXAMPLE
<?php
$myDao 
= new \app\model\Customers();
$myDao->beginTransaction();
$myDao->setForUpdate(TRUE);
$row $myDao->getById(18);
$row['is_visible'] = 'Y';
$myDao->store($rowFALSE);
$myDao->commit;

 Method commit()
DESCRIPTION Commits the data changed in the table.
EXAMPLE
<?php
$row 
= array('id'=>18,'name'=>'MARTIN','city'=>'Paris');
$myDao = new \app\model\Customers();
$myDao->beginTransaction();
$result $myDao->store($rowFALSE);
$myDao->commit();

 Method rollback()
DESCRIPTION Cancels in the database the SQL transaction explicitly initiated by a call to the beginTransaction() method of the DAO.
EXAMPLE
<?php
$row 
= array('id'=>18,'name'=>'MARTIN','city'=>'Paris');
$myDao = new \app\model\Customer();
$myDao->beginTransaction();
$result $myDao->store($row);
$myDao->rollback();

Class \SimpleDAO

The ZnetDK class \SimpleDAO offers an easy and quick way to operate on a single SQL table or view.

As it is a concrete class, no need to create any DAO class, just instantiate a \SimpleDAO object by specifying in the constructor the SQL table name.
The \SimpleDAO class is derived from the \DAO class and so gives access to all its methods.

Here is an example of usage of the \SimpleDAO class.

EXAMPLE
<?php
$contactsDao 
= new \SimpleDAO('contacts');
$rowsFound = array();
$rowCount $contactsDao->getRows($rowsFound'name');
?>

 Constructor _construct()

DESCRIPTION Constructor of the \SimpleDAO class to instantiate an object used in order to access the SQL table specified in parameter.
Once instantiated, a SimpleDAO object can also access to all protected and public properties and methods of the \DAO class.
PARAMETERS
$tableName String Name of the SQL table or view to browse or to update.
RETURNED VALUE \SimpleDAO New object of type SimpleDAO.
EXAMPLE
<?php
$dao 
= new \SimpleDAO('customers');

 Method getRows()

DESCRIPTION Returns the rows of the SQL table specified in the object constructor, also taking the following POST parameters into account:
 first: the first line to return,
 count: the number of rows to return,
 sortfield: the sorted column,
 sortorder: the sort order ('1' or '-1'),
 keyword: the keyword to search for in the specified rows' column through the setKeywordSearchColumn() method.
PARAMETERS
&$rowsFound Array The rows found in the SQL table that are returned by reference by the method.
$defaultSortFields String OPTIONAL, a comma-separated list of the columns involved in row sorting, just like the ORDER BY clause in SQL.
These sort criteria are only applied if the POST parameters sortfield and sortorder are not set.
For example: 'city ASC, id DESC'.
RETURNED VALUE Array Total number of rows that exist in the SQL table if the keyword POST parameter is empty.
Otherwise this number is the total number of rows found in the SQL table for the specified keyword.
In all cases, this total number is always greater than or equal to the number of rows returned in the $rowsFound variable.
EXAMPLE
<?php
/* POST parameters: first='0', count='10', keyword='paul' */
$dao = new \SimpleDAO('customers');
/* keywords searched into the table's column 'name' */
$dao->setKeywordSearchColumn('name');
$customers = array();
/* Rows found are sorted by 'name' (sorting POST parameters not set) */
$total $dao->getRows($customers'name ASC');

 Method getRowsForCondition()

DESCRIPTION Returns the rows matching the specified condition and values.
PARAMETERS
$condition String Condition to apply to select the SQL table's rows.
It is given as a standard SQL WHERE clause condition with a question mark (i.e ?) as placeholder for each value set as parameter.
For example: 'color = ? AND type = ?'.

$value1 [,$value2, $valueN] mixed Values matching each question marks existing within the SQL condition ($condition).
The first value is mandatory. The next values are optionals.
The number of values passed as parameter of this method depends on the number of existing question marks within the SQL condition.
For example: [
['id' => '5', 'color' => 'Blue', 'type' = 'public'],
['id' => '8', 'color' => 'Red', 'type' => 'private']
].
RETURNED VALUE Array The rows found as an array of associative arrays where the keys match the table's column names.
EXAMPLE
<?php
$dao 
= new \SimpleDAO('customers');
$condition 'name LIKE ?';
$value 'jean';
$result $dao->getRowsForCondition($condition"%{$value}%");

 Method getSuggestions()

DESCRIPTION Returns the suggestions matching the keyword set through the query POST parameter.
The setKeywordSearchColumn() method must be called first to specify the SQL column name in which the keyword is searched in.
PARAMETERS
$count Integer OPTIONAL, maximum number of suggestions to return (value 10 by default).
RETURNED VALUE Array | FALSE The suggestions as an array of associative arrays where each subarray has 'value' and 'label' keys.
For example: [['value' => '7', 'label' => 'Jean MORISSON'], ['value' => '59', 'label' => 'Jean CARRY']]
Returns FALSE if the table's column name is not set through the setKeywordSearchColumn() method.
EXAMPLE
<?php
/* POST parameter: query='jean' */
$dao = new \SimpleDAO('customers');
$dao->setKeywordSearchColumn('name');                
$suggestions $dao->getSuggestions(20);

 Method setKeywordSearchColumn()

DESCRIPTION Specifies the name of the SQL table column in database in which the keywords are searched in.
This method is invoked before calling the getRows() and getSuggestions() methods.
PARAMETERS
$columnName String Column name of the table set when calling the SimpleDAO class constructor.
EXAMPLE
<?php
$dao 
= new \SimpleDAO('customers');
$dao->setKeywordSearchColumn('name');

Data Validation

Form data sent to the web server can be verified before storage using a custom PHP class in charge of their validation.

Class \Validator

The \Validator class is abstract and can only be instantiated through a derived class that implements:
  • initVariables() method to specify the names of the HTTP request data to check,
  • Optionally, the initOptionalVariables() method to indicate the names of the HTTP request data whose values are not mandatory,
  • Finally, a check_[dataName]() control method for each data of the HTTP request to be checked. For example, it will be called check_email() to check the POST data named email.

The custom derived class is generally stored into the INSTALL_DIR/applications/default/app/validator/ folder.

EXAMPLE: custom MyValidator class derived from the \Validator class
<?php
namespace app\validator;
class 
MyValidator extends \Validator {
    protected function 
initVariables() {
        return array(
'user_name','user_email');
    }

    protected function 
check_user_name($value) {
        
// 100 characters maximum
        
if (strlen($value) > 100) {
            
$this->setErrorMessage('User name is too long!');
            return 
FALSE;
        }
        return 
TRUE;
    }

    protected function 
check_user_email($value) {
        
// Must be a valid email address
        
if (!filter_var($valueFILTER_VALIDATE_EMAIL)) {
            
$this->setErrorMessage('Email address invalid!');
            return 
FALSE;
        }
        return 
TRUE;
    }
}
?>

Checking data with a validator object

The application controller, at the origin of the data verification request, instantiates an object derived from the Validator class and evaluates the quality of the HTTP data before their processing by calling:
  • In option, setCheckingMissingValues() method to specify that empty data (null) are also checked,
  • validate() method to check data,
  • getErrorVariable() method to obtain the name of the first POST data detected in error,
  • getErrorMessage() method to get the error message returned by the check_[dataName]() method that detected the error,
  • In option, getValues() method to get the values of the POST data that have been checked.
EXAMPLE: Call of the custom MyValidator class for data checking
<?php
namespace app\controller;
class 
MyController extends \AppController {

    protected function 
action_save() {
        
$request = new \Request();
        
$response = new \Response();
        
// Form data validation
        
$validator = new \app\validator\MyValidator();
        
$validator->setCheckingMissingValues();
        if (!
$validator->validate()) {
            
$response->setFailedMessage(NULL$validator->getErrorMessage(),
                
$validator->getErrorVariable());
            return 
$response;
        }
        
// Storage
        
$request = new \Request();
        
$row $validator->getValues();
        
$row['id'] = $request->id;
        
$dao = new \SimpleDAO('my_users');
        
$dao->store($row);
        
$response->setSuccessMessage('User''Stored successfully.');
        return 
$response;
    }

}
?>

User Data

The data stored in session for the logged in user are managed through the \UserSession class.
The informations stored in database for the logged in user are retrieved through the \controller\Users class.

Class \UserSession

User sessions are managed via the \UserSession ZnetDK class that is used to get informations about the logged in user and to store custom data.

The session is started automatically and so doesn't need to be started explicitly.

 Method setCustomValue()

DESCRIPTION Stores in the user's session a value for the specified variable name.
Please note that text data is sanitized before it is stored in session.
So to store data in HTML format, the data must first be converted before storage calling the htmlentities() PHP function and restored after session read by calling the html_entity_decode() PHP function.
PARAMETERS
$variableName String Name of the variable used to store the value in session.
$value mixed Value to store in session.
EXAMPLE
<?php
\UserSession::setCustomValue('myVarInSession'18);
?>

 Method getCustomValue()

DESCRIPTION Retrieves in the user's session, the value previously stored for the specified variable name.
PARAMETERS
$variableName String Name of the variable used to store the value in session.
RETURNED VALUE mixed | NULL The value stored in session for the specified variable name.
Returns NULL if no variable exists in the user's session for the name of variable specified in parameter.
EXAMPLE
<?php
$myValueInSession 
= \UserSession::getCustomValue('myVarInSession');
?>

 Method removeCustomValue()

DESCRIPTION Removes in the user's session, the value previously stored for the specified variable name.
PARAMETERS
$variableName String Name of the variable to remove from the user's session.
RETURNED VALUE Boolean Returns TRUE if the variable exists and has been removed, FALSE if the specified variable does not exist in session.
EXAMPLE
<?php
\UserSession::removeCustomValue('myVarInSession');
?>

 Method getLoginName()

DESCRIPTION Returns the login name stored in session for the logged in user.
RETURNED VALUE String The login name of the logged in user or NULL if no user is logged in.
EXAMPLE
<?php
$loginName 
= \UserSession::getLoginName();
?>

 Method getLanguage()

DESCRIPTION Returns the language ISO 639-1 code stored in the user session.
RETURNED VALUE String Language ISO 639-1 code.
EXAMPLE
<?php
$userLang 
= \UserSession::getLanguage();
?>

 Method isAuthenticated()

DESCRIPTION Indicates whether the user is authenticated or not.
PARAMETERS
$silent = FALSE Boolean if TRUE, no 401 HTTP error is thrown.
RETURNED VALUE Boolean TRUE if user is authenticated, FALSE otherwise.
EXAMPLE
<?php
if (!\UserSession::isAuthenticated(TRUE)) {
    
// User not authenticated!
}
?>

Class \controller\Users

The \controller\Users class is used to get informations stored in database about the logged in user.

 Method getUserName()

DESCRIPTION Returns the user name of the currently logged in user.
RETURNED VALUE String User name or NULL if the user name can't be read in the database or if no user is authenticated.
EXAMPLE
<?php
$userName 
= \controller\Users::getUserName();
?>

 Method getUserEmail()

DESCRIPTION Returns the user email of the currently logged in user.
RETURNED VALUE String User email or NULL if the user email can't be read in the database or if no user is authenticated.
EXAMPLE
<?php
$userEmail 
= \controller\Users::getUserEmail();
?>

 Method hasProfile()

DESCRIPTION Indicates whether the user has the specified profile or not.
RETURNED VALUE Boolean TRUE if user has the specified profile, otherwise FALSE.
EXAMPLE
<?php
if (\controller\Users::hasProfile('Manager')) {
    
// User is manager
}
?>

 Method hasMenuItem()

DESCRIPTION Indicates whether the logged in user has access to the specified menu item.
PARAMETERS
$menuItem String The menu item (name of the view without the .php extension).
RETURNED VALUE Boolean TRUE if the user has access to the specified menu item, otherwise FALSE.
EXAMPLE
<?php
if (\controller\Users::hasMenuItem('myview')) {
    
// User has access to "myview.php"
}
?>

Miscellaneous Tools

The ZnetDK framework provides useful utility classes in PHP for data conversion, formatted dates, data writing to log files, ...

Class \General

 Method getCurrentW3CDate()

DESCRIPTION Get the current date in W3C format.
PARAMETERS
$withTime Boolean When set to TRUE (FALSE by default), the time is also returned on the right of the formated date.
RETURNED VALUE String the current date in W3C format ('Y-m-d').
EXAMPLE
<?php
echo \General::getCurrentW3CDate();
?>

 Method getFilledMessage()

DESCRIPTION Replace in the text of the message specified for the first parameter, the placeholders %1, %2, ... by the text value specified in the same order for the next paramaters.
This method is particularly useful when the string passed as first parameter is a PHP constant defined into the locale.php script.
PARAMETERS
$message String Original message in which the placeholders %1, %2, ... are to be replaced by the values specified as other parameters.
$text1 String Text for replacement of the placeholder %1.
$text2 String Text for replacement of the placeholder %2 if exists.
$textN String Text for replacement of the placeholder %N if exists.
RETURNED VALUE String Message filled with the pieces of text specified in input parameters.
EXAMPLE
<?php
echo \General::getFilledMessage('Your car is %1 and %2.','blue','yellow');
/* Display: Your car is blue and yellow. */
?>

 Method writeErrorLog()

DESCRIPTION Add an error entry in the ZnetDK error log.
PARAMETERS
$origin String Text specifying the origin of the error.
$textError String Text of the error.
EXAMPLE
<?php
\General::writeErrorLog('MYAPP''Error detected...');

Class \Convert

 Method toMoney()

DESCRIPTION Format the specified number for display as money.
PARAMETERS
$number mixed Number to convert as a string or a numeric value.
$withCurrencySymbol Boolean Specifies whether the currency symbol is to be added to the formatted number (added by default).
$numberOfDecimals Integer Number of decimals of the converted number.
RETURNED VALUE String Number formated as a money.
EXAMPLE
<?php
$myMoney 
= \Convert::toMoney(3451.7399);
?>

 Method W3CtoLocaleDate()

DESCRIPTION Formats the specified W3C string date using the locale settings of the application.
If the date is followed by a time, this time is kept as is.
PARAMETERS
$W3CDate String Date formatted in W3C format ('Y-m-d').
RETURNED VALUE String Date formatted according to the current locale settings.
EXAMPLE
<?php
$myDate 
= \Convert::W3CtoLocaleDate('2013-04-22');
?>

ZnetDK constants

The following PHP constants can be used in the views and in the controllers to get absolute or relative path of specific ZnetDK folders.

Path constants

 Constant ZNETDK_APP_NAME

Name of the subfolder containing the source code and the documents of the running application.

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_APP_NAME// Display of default
?>

 Constant ZNETDK_APP_ROOT

Absolute path of the folder containing the files of the running application.

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_APP_ROOT// Display of /home/hosting999/www/znetdk/applications/default
?>

 Constant ZNETDK_APP_URI

Relative file path of the directory containing the web resources of the application.

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_APP_URI// Display of /znetdk/applications/default/public/
?>

 Constant ZNETDK_ROOT

Abdolute file path of the root directory of ZnetDK (installation folder).

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_ROOT// Display of /home/hosting999/www/znetdk/
?>

 Constant ZNETDK_ROOT_URI

Relative path of the root directory of ZnetDK (installation folder).

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_ROOT_URI// Display of /znetdk/
?>

 Constant ZNETDK_CORE_ROOT

Abdolute file path of the core directory of ZnetDK.

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_CORE_ROOT// Display of /home/hosting999/www/znetdk/engine/core
?>

 Constant ZNETDK_MOD_ROOT

Abdolute file path of the modules directory of ZnetDK.

EXAMPLE
<?php
/* If ZnetDK is installed into the /home/hosting999/www/znetdk/ folder
    and if the Starter Application is currently running... */
echo ZNETDK_MOD_ROOT// Display of /home/hosting999/www/znetdk/engine/modules
?>

 Constant CFG_ZNETDK_IMG_DIR

Relative file path of the images directory of ZnetDK.

EXAMPLE
<?php
echo CFG_ZNETDK_IMG_DIR// Display of engine/public/images
?>