The mapper is the connection between your business layer (Controller) and data layer (Model / DBTable) and is used to reduce the complexity we find when binding the model and communicating with entities. The Mapper is used to format data retrieved from the data layer before giving it back to the business layer.
#### In this section we will handle:
From Mapper to DBTable
Mappers are created in the modules/{YOUR-MODULE-NAME}/models/mapper/ folder. By default, the name of a mapper begins with "Mapper" (you may change this configuration in the app.php).
A customer mapper is created in the example below.
<?php
namespace App\models\mapper;
use sFire\MVC\Mapper;
class MapperCustomer extends Mapper {
public function __construct() {
$this -> setDBTable('customer');
}
}
?>
As you can see, the constructor calls the setDBTable method. This method lets you set a new DBTable name that will interact with DBTable and will be converted to the name of the DBTable file which is stored in modules/{YOUR-MODULE-NAME}/models/dbtable/. In this case the filename will be "DBTableCustomer.php". The filename is prefixed with "DBTable" which can be configurated in the app.php.
Imagine that you want to retrieve a customer by it's id. From the controller you create a new instance of the mapper:
use App\models\mapper\MapperCustomer;
$customerMapper = new MapperCustomer();
$id = $customerMapper -> getById(25);
var_dump($id);
Be sure to use the correct namespace because your module can have another name than "App".
We have created a new mapper instance and now it is time to create the getById method in the mapper:
public function getById($id) {
$id = $this -> dbtable() -> getCustomerById($id) -> current();
return $id;
}
In this case, we are going to retrieve the customer id from a database so we use the dbtable method. This method will use the variable that we have set earlier with the setDBTable method to load a new instance of the "DBTableCustomer.php".
If you wish to retrieve data from another DBTable, you can set the first and only parameter of the dbtable method:
$id = $this -> dbtable('OtherCustomer') -> getCustomerById($id) -> current();
In this case the DBTable that will be loaded is "DBTableOtherCustomer.php".