PHP code example of philippgrashoff / atkdatamodeltraits

1. Go to this page and download the library: Download philippgrashoff/atkdatamodeltraits library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

philippgrashoff / atkdatamodeltraits example snippets


class SomeModel extends Model
{
    use CreatedDateAndLastUpdatedTrait;

    protected function init(): void
    {
        parent::init();
        $this->addCreatedDateFieldAndHook();
        $this->addLastUpdatedFieldAndHook();
    }
}

class SomeModel extends Model
{
    use UniqueFieldTrait;

    protected function init(): void
    {
        parent::init();
        $this->addField('unique_field');
    }
    
    $this->onHook(
        Model::HOOK_BEFORE_SAVE,
        function(self $entity, bool $isUpdate) {
            while(!$entity->isFieldUnique('unique_field')) {
                //some function which recalculates field value.
            }
        }
    );
}

class SomeModel extends Model
{  
    use CryptIdTrait;

    protected function init(): void
    {
        parent::init();
        $this->addCryptIdFieldAndHooks('crypt_id');
    }

    /**
     * Custom implementation if cryptic ID format, In this case XXXXX-XXXXX-XXXXX
     */
    protected function generateCryptId(): string
    {
        $cryptId = '';
        for ($i = 0; $i < 3; $i++) {
            if($i > 0) {
                $cryptId .= '-';
            }
            for ($j = 0; $j < 5; $j++) {
                $cryptId .= $this->getRandomChar();
            }
        }

        return $cryptId;
    }
}