DB CRUD in seminars

Crud mapper concepts

CRUD mapper is a trait that designed to simplify loading and saving data to database. It might look similar to data_object, however it has substantial differences and idea behind it:

  • crud_mapper is not intended to reinvent the Active Record. AR has many disadvantages, like reduced testability, and more important mixing domain logic with DB operations.
  • crud_mapper solo purpose is to reduce verbosity of loading and saving data, while taking some safety measures during mapping/unmapping of record stdClass to crud class and allow to easily replace it if needed.
  • crud_mapper uses composition instead of inheritance allowing Domain Driven Design implementations of logic
  • crud_mapper require less definitions related to DB setting convention over configuration
  • crud_mapper can be used for creating instances from webapi calls and provide consistent results with DB.
  • In crud_mapper all columns are required and automatically checked from database table definition.
  • crud_mapper does not implement save(), load(), or delete() methods to allow changing implementation when required without changing API and add domain logic in this methods prior saving/deletion or loading.

How to use crud_mapper

  1. Add "use mod_facetoface\traits\crud_mapper" to class definition.
  2. Add const DBTABLE to class definition with table name.
  3. Make sure that all fields that are in database exist in class.
  4. Implement public function save() that optionally make sure that data are correct to be saved and call $this→crud_save();
  5. Implement public function load() that will call $this→crud_load() and optionally prepare some other data.

Optionally, only if required methods map_object() and unmap_object() can be exposed to public interface, but it is not encouraged unless used for web API, because in this case we allow some free form data to be put in instance. As a  safety measure map_object() will check that all fields are set in object and trigger debugging message otherwise. 

 Example crud enabled class implementation

Instantiation of crud mapped classes

All crud enabled classes are expected to have public function load(int $id) which will load data from table.

When there needed other methods of data loading, but there expected only few of them, then they should be created as static methods inside class and named from create_from_* (e.g. seminar_event::create_from_seminar(seminar $seminar)). In this way static function have full access to all private properties during object preparation.

If object expected to be created in many ways with different conditions, then separate class name *_repository (e.g. class seminar_repository) and have only methods to create instances of target class.