Mapper is the last ORM layer which communicates with database. In contrary to repository, mapper is storage specific, even more, also database specific. Everything database specific should be implemented only in mapper layer. Orm comes with two predefined mappers: ArrayMapper, which works over PHP array, and DbalMapper, which uses Nextras\Dbal database abstraction layer.
Array mapper allows you to work with Orm without database.
ArrayMapper
can be heavily used in tests. Mocking repositories and
entities is not so easy, therefore you can use TestMapper
, which
will allow you to pass orm dependencies as in production mode, but test will not
require any type of database connection. All Orm integrations tests are also run
with Test mappers storage.
Collection results form Array mapper are returned as
ArrayCollection
instance.
Dbal mapper uses Nextras Dbal library. Both Nextras Dbal and Orm support these database engines:
Dbal mapper is aliased as Nextras\Orm\Mapper\Mapper
class.
Collection results from Dbal mapper are returned as a
DbalCollection
(if you use Dbal's QueryBuilder) or as an
ArrayCollection
(if you use raw SQL query).
To set mapper's database table name set $tableName
property or override getTableName()
method.
class BooksMapper extends Nextras\Orm\Mapper\Mapper
{
protected $tableName = 'tbl_book';
// or
public function getTableName()
{
return 'tbl_book';
}
}
If it is impossible to filter data by repository API, you can write more
detailed filtering in mapper. Dbal mapper allows quering by
Nextras\Dbal\QueryBuilder\QueryBuilder
or directly by SQL. Query
builder instance will be injected into DbalCollection, raw SQL query will be
executed and returned rows will be wrapped up in ArrayCollection instance.
DbalCollection is lazy, so it is always better to use dbal's query builder.
You can get new query builder instance by calling the builder()
method. An instance of the current database connection is available in
$connection
property.
class BooksMapper extends Nextras\Orm\Mapper\Mapper
{
public function getRandomBooksByBuilder(): Nextras\Orm\Collection\ICollection
{
return $this->toCollection(
$this->builder()->addOrderBy('RAND()')
);
}
public function getRandomBooksByQuery(): Nextras\Orm\Collection\ICollection
{
return $this->toCollection(
$this->connection->query('SELECT * FROM tbl_books ORDER BY RAND()')
);
}
}
See repository chapter to learn how to access methods from mapper layer.