Persistence (DAO)

This is the part that deals with the management of operations related to data access support.

1. Summary of useful methods of data manipulation

We have the “\muuska\dao\DAO” interface which takes care of the persistence. By default, it offers a set of methods that we are used to using.

– Method

    • add
      • Description : Add an object. If the object has the attributes “creationDate” or “lastModifiedDate”, the values will be filled in automatically. If the object class is defined in auto-increment, the value of the object identifier will be automatically filled in on the object. This method throws an exception if the object is not valid.
      • Parameter :
        • model : the object to add.
        •  saveConfig (optional) : it is an object of the class \muuska\dao\util\SaveConfig allowing to specify the data saving options.
      • Return type  : Boolean
    • update
      • Description : Modifies an existing object. If the object has an “lastModifiedDate” attribute, it’s value will be filled in automatically. This method signifies an exception if the object is not valid.
      • Parameter : 
        • model : The object to modify.
        • saveConfig (optional) : it is an object of class\muuska\dao\util\SaveConfig allowing to specify options for saving data.
      • Return type  : Boolean
  • save
    • Description : Registers an object. If the object identifier is entered, it will make a modification otherwise, it will make the addition. This method is only functional for classes with an auto-increment identifier. This method throws an exception if the object is not valid.
    • Parameter : 
      • model : The object to register
      • saveConfig (optional) : it is an object of the \muuska\dao\util\SaveConfig class allowing to specify the data saving options
    • Return type  : Boolean
  • updateMultipleRows
    • Description : Edit information for multiple rows from row data from template data. This method throws an exception, the model data is not valid.
    • Parameter : 
      • model : The object from which the data will be retrieved
      • saveConfig (optional) : it is an object of class \muuska\dao\util\SaveConfig allowing to specify options for saving data.
    • Return type :Boolean
  • updateMultipleRowsFromArray
    • Description : Modifies the information of multiple rows from the row data from the data present in an associative array. This method throws an exception the data is not valid.
    • Parameter : 
      1. data : associative table representing the data to modify.
      2. saveConfig (optional) : it is an object of class\muuska\dao\util\SaveConfig allowing to specify options for saving data.
    • Return type : Boolean
  • changeValue
    • Description : Modifies the value of a specific attribute. Throws an exception if the object’s class does not have the specified attribute.
    • Parameter : 
      • model : The object on which we want to change the value.
      • field : The name of the attribute.
      • value : The new value.
    • Return type : Boolean
  • changeValueOnMultipleRows
    • Description : Changes the value of a specific attribute on multiple lines. Throws an exception if the object’s class does not have the specified attribute.
    • Parameter : 
      • field : The name of the attribute.
      • value : The new value.
      • saveConfig (optional) : it is an object of class \muuska\dao\util\SaveConfig allowing to specify options for saving data.
  • activate
    • Description : Activate an object. Throws an exception if the object’s class does not have the attribute. “Active“.
    • Parameter : 
      • model : The object to activate.
    • Return type : Boolean
  • deactivate
    • Description : Disables an object. Throws an exception if the object’s class does not have the “active” attribute.
    • Parameter : 
      • model : The object to deactivate.
    • Return type : Boolean
  • setModelNewPosition
    • Description : Automatically changes the position of an object. By giving it the value of the position of the last object + 1
      Throws an exception if the object’s class does not have the “position” attribute.
    • Parameter : 
      • model : The object to modify.
  • delete
    • Description : Removes an object.
    • Parameter : 
      • model : The object to delete.
      • deleteConfig (optional) : it is an object of the \muuska\dao\util\DeleteConfig class used to specify the data deletion options.
    • Return type : Boolean
  • deleteMultipleRows
    • Description : Deletes multiple records.
    • Parameter : 
      • deleteConfig (optional) : it is an object of the class \muuska\dao\util\DeleteConfig allowing to specify the options for the deletion of data.
  • clearData
    • Description : Clears all data then resets DAO.
    • Return type : Boolean
  • getById
    • Description : Retrieves an object by its identifier. Returns “null” if the object does not exist.
    • Parameter : 
      • id : Object identifier.
      • selectionConfig (optional) : it is an object of the \muuska\dao\util\SelectionConfig class used to specify data selection options.
      • returnEmptyModelIfNotFound (optional) : Allows to specify that you want an empty template to be returned if no object is found. If you set this parameter to “true”, you will need to call the “isLoaded” method on the object definition to check if the object has been found. Default value “false”
    • Return type : Object
  • getUniqueModel
    • Description : Collect a single item. Returns “null” if the object does not exist.
    • Parameter :  
      • selectionConfig (optional) : it is an object of class \muuska\dao\util\SelectionConfig to specify data selection options.
      • returnEmptyModelIfNotFound (optional) : Allows to specify that we want an empty model returned if no object was found. If you set this parameter to “true”, you will need to call the “isLoaded” method on the object definition to check if the object has been found. Default value “false”.
  • getModelValue
    • Description : Retrieves the value of a specific field.
    • Parameter :  
      • selectionConfig (optional) : it is an object of class \muuska\dao\util\SelectionConfig to specify data selection options.
      • field : The name of the field
  • getData
    • Description : Get a list of objects.
    • Parameter :  
      • selectionConfig (optional) : it is an object of class \muuska\dao\util\SelectionConfig to specify data selection options.
    • Return type : Collection of objects
  • getDataTotal
    • Description : Retrieves the number of data.
    • Parameter :  
      • selectionConfig (optional) : it is an object of class \muuska\dao\util\SelectionConfig to specify data selection options.
  • loadAssociatedObject
    • Description : Load an external object
    • Parameter :  
      • model : the current object
      • field : The field with which the external object is associated.
      • selectionConfig (optional) : it is an object of the \muuska\dao\util\SelectionConfig class used to specify data selection options.
      • returnEmptyModelIfNotFound (optional)
    • Return type : Object
  • loadMultipleAssociatedObjects
    • Description :  Load the objects of a multiple association
    • Parameter :  
      • model  :  the current object.
      • associationName  : The name of the multiple association.
      • selectionConfig (optional) : it is an object of class \muuska\dao\util\SelectionConfig to specify data selection options.
    • Return type : Collection of objects
  • getParents
    • Description : Returns the list of parent objects of the current object.
      Throws an exception if the object’s class does not have the “parentId” attribute.
    • Parameter :  
      • model  : the current object.
      • selectionConfig (facultatif)
    • Return type : Collection of objects
  • getChildren
    • Description : Returns the list of child objects of the current object.
      Throws an exception if the object’s class does not have the “parentId” attribute.
    • Parameter :
      • model  : the current object.
      • selectionConfig (facultatif)
    • Return type : Collection of objects
  • getForeignDAO
    • Description : Returns the DAO of an external object.
    • Parameter : 
      • field : Control to which the external DAO is associated.
    • Return type : DAO
  • getMultipleAssociationDAO
    • Description : Returns the DAO of a multiple association
    • Parameter : 
      • associationName : The name of the multiple association.
    • Return type : DAO

2. Data manipulation

For this part, we will create a “TestDao” controller.  We are going to create a “test-dao” control.

a. Initialization

Creating the test-dao control

Go to your controller/front folder and create a TestDAOController class

<?php
namespace myapp;

use muuska\project\AbstractSubApplication;

class FrontSubApplication extends AbstractSubApplication
{
    public function createController(\muuska\controller\ControllerInput $input) {
        $result = null;
        if ($input->checkName('hello-world')) {
            $result = new \myapp\controller\front\HelloWorldController($input);
        }elseif ($input->checkName('test-model')) {
            $result = new \myapp\controller\front\TestModelController($input);
        }elseif ($input->checkName('test-dao')) {
            $result = new \myapp\controller\front\TestDAOController($input);
        }
        return $result;
    }
}

Enter the url http://localhost/muuska/en/test-dao to access it

Retrieving an instance of the DAO

To retrieve the instance of a DAO, add the following statement at the controller level :

$libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());

The “getDAO” method takes as parameter the definition of the object from which we want to retrieve the DAO.

b. Registration

– The \muuska\dao\util\SaveConfig class

This class has several methods for defining recording options :

  • setExludedFields 

indicate the fields to be excluded during the registration.

  • setSpecificFields

Indicate the specific fields to save.

  • createAssociatedFieldSaveConfig

Creates and adds the record configuration of an associated object. It takes as parameter the name of the field on which the reference of the external object is defined.

  • createMultipleSaveAssociation

Create a configuration for a multiple association

– Adding

$libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
$library = new Library();
$library->setName('My library');
$library->setOpeningTime('Monday');
$library->setAccessibility(Accessibility::PUBLIC);
$library->setDescription('My library desc');

/*Création de l'adresse*/
$address = AddressDefinition::getInstance()->createModel();
$address->setPropertyValue('address', '4500 NY');
$address->setPropertyValue('city', 'New york');
$address->setPropertyValue('state', 'New york');
$address->setPropertyValue('country', 'US');

/*Création de la spécialité */
$specialityDao = $this->input->getDAO(SpecialityDefinition::getInstance());
$speciality1 = SpecialityDefinition::getInstance()->createModel();
$speciality1->setPropertyValue('name', 'Art');

/*Ajout de la spécialité */
$specialityDao->add($speciality1);

$libSpeciality1 = LibrarySpecialityDefinition::getInstance()->createModel();
$libSpeciality1->setPropertyValue('specialityId',$speciality1->getPropertyValue('id'));

$speciality2 = SpecialityDefinition::getInstance()->createModel();
$speciality2->setPropertyValue('name', 'Musique');

/*Ajout de la spécialité*/
$specialityDao->add($speciality2);

$libSpeciality2 = LibrarySpecialityDefinition::getInstance()->createModel();
$libSpeciality2->setPropertyValue('specialityId',$speciality2->getPropertyValue('id'));

/*Modification de l'adresse de la bibliothèque*/
$library->setAssociated('addressId', $address);

/*Ajout des spécialités à la bibliothèque */
$library->addMultipleAssociated('specialities', $libSpeciality1);
$library->addMultipleAssociated('specialities', $libSpeciality2);

/*Création du SaveConfig*/
$saveConfig = $this->input->createSaveConfig();

/*On demande d'enregistrer l'adresse avant d'enregistrer la bibliothèque*/
$saveConfig->createAssociatedFieldSaveConfig('addressId');

/*Instruction pour associer les spécialités à la bibliothèque après son enregistre-ment*/
$saveConfig->createMultipleSaveAssociation('specialities');
$libraryDao->add($library, $saveConfig);

Run the controller then check your database to verify the records.

– The modification

protected function processUpdate() {
    $libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
    $library = $libraryDao->getById(1);
    $library->setName('My library updt');
    $library->setAccessibility(Accessibility::PRIVATE);
    $libraryDao->update($library);
}

Run the controller then check your database to verify the records.

– Editing multiple

protected function processMultipleUpdate() {
    $libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
    $library = new Library();
    $library->setName('My library updt multiple');
    $library->setAccessibility(Accessibility::PRIVATE);
    $saveConfig = $this->input->createSaveConfig();
    
    /*Ajout des options pour la restriction*/
    $saveConfig->addRestrictionFieldFromParams('openingTime', 'Monday');
    
    $libraryDao->updateMultipleRows($library, $saveConfig);
}
	

– Changing a value

protected function processChangeValue() {
    $libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
    $saveConfig = $this->input->createSaveConfig();
    
    /*Ajout des options pour la restriction*/
    $saveConfig->addRestrictionFieldFromParams('openingTime', 'Monday');
    
    $libraryDao->changeValueOnMultipleRows('name', 'My library value changed', $saveConfig);
}

c. Selection

– The class “muuska\dao\util\SelectionConfig”

This class defines how the data will be recovered (the selection criteria, sort criteria, the limit of data to retrieve).

The following table describes the attributes of the class “muuska\dao\util\SelectionConfig”

  • Attribut 
    • langEnabled
      • Description : Indicate if you will retrieve the values of translatable fields
      • Data type : boolean
      • default : true
    • allLangsEnabled
      • Description : Indicate if you will retrieve the values of translatable fields in all available languages.
      • Data type : boolean
      • default : false
    • lang
      • Description : The language in which the data will be retrieved
        (If the Model concerned takes multilingual into account)
      • Data type : String
    • dataCountingEnabled
      • Description : Indicate if you will also get the total number of data.
      • Data type : boolean
      • default : false
    • start
      • Description :  The index where data reading should begin. (The first index is 0).
      • Data type : integer
      • default : 0
    • limit
      • Description :  The maximum number of data to recover. If this field is not specified, all data will be recovered.
      • Data type : integer
      • default : 0
    • logicalOperator
      • Description :  The logical operator (AND or OR) to use between restrictions. The class “muuska\constant\operator\LogicalOperator” has constants for use for this attribute.
      • Data type : integer
      • default : 1 : AND_
    • virtualDeletedEnabled
      • Description : Specifies whether items that were removed virtually be selected.
      • Data type : boolean
      • default : false
    • onlyActive
      • Description : Indicates if only wants the active elements (Only if the Model to an “active” attribute).
      • Data type : boolean
      • default : false
    • restrictionFields
      • Description : List of fields where restrictions are applied.
        The elements of this table are of type “muuska\dao\util\FieldRestriction”.
      • Data type : table
    • sortOptions
      • Description : List of fields where the sort options are configured.
        The elements of this array are of type “muuska \ dao \ util \ SortOption.
      • Data type : table
    • selectionAssociations
      • Description : List of fields where the associated data selection options are configured.
        The elements of this array are objects of the “muuska \ dao \ util \ SelectionAssociation” class.
      • Data type : table

– Standard selection

protected function processSelect() {
    $libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
    $data = $libraryDao->getData();
    var_dump($data);
}

var_dump variable

– Selection with total number of data 

protected function processSelectWithTotal() {
    $libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
    $selectionConfig = $this->input->createSelectionConfig();
    $selectionConfig->setDataCountingEnabled(true);
    $selectionConfig->setLimit(1);
    $data = $libraryDao->getData($selectionConfig);
    var_dump('total without limit : ', $data->getTotalWithoutLimit());
    var_dump($data);
}

Result

total data nomber

– Retrieving information on objects associated with the Model

Here is a list of methods in the class “core \ utilities \ dao \ SelectionConfig” for managing the objects associated with a Model.

  • methods
    • addSelectionAssociation
      • Description : Adds an association configuration to the list (selectionAssociations)
      • Parameter : 
        • selectionAssociation : it is a class object “muuska\dao\util\SelectionAssociation”.
        • key (optional) : the key of the object in the list. If this value is not given then the name of the concerned field will be used as the key.
    • hasAssociation
      • Description : Checks if a key exists in the association list.
      • Parameter : 
        • key : the key sought.
      • Return type : boolean
    • getSelectionAssociationByKey
      • Description : Returns an association based on a key.
        If the searched key does not exist, “null” will be returned.
      • Parameter : 
        • key : the key sought.
        • getNewIfNotExist (optional) : Allows you to indicate whether you want a new object to be returned in case the one sought does not exist. (Default value: “false”).
        • addToListIfNotExist (optional) : Used to indicate whether you want the new object to be created in case the one sought does not exist is added to the list. (Default value: “false”).
      • Return type : Selection Association
    • setSelectionAssociationParams
      • Description : Adds or Modifies (If it already exists) an association from the parameters.
      • Parameter : 
        • fieldName : the name of the field on which there is the reference.
        • joinType (optional) : The type of join to use. The class “muuska \ dao \ constant \ JoinType” has constants for use in this setting. (Default value: JoinType :: LEFT).
        • retrievingEnabled (optional) : Indicates whether or not you want to retrieve the information of the associated object. (Default: true).
        • langEnabled (optional) : Indicates whether to retrieve the values of the translatable fields. (Default: true).
        • langEnabled (optional) : Indicates whether you want to retrieve the values of the translatable fields in all the available languages. (Default: false).

Example

protected function processSelectAssociation() {
    $libraryDao = $this->input->getDAO(LibraryDefinition::getInstance());
    $selectionConfig = $this->input->createSelectionConfig();
    $selectionConfig->setSelectionAssociationParams('addressId');
    $data = $libraryDao->getData($selectionConfig);
    foreach ($data as $object) {
        var_dump($object->getAssociated('addressId'));
    }
}

processSelectorAction

 

Leave a Reply

Your email address will not be published. Required fields are marked *