Skip to content

Latest commit

 

History

History
120 lines (85 loc) · 3.19 KB

README.md

File metadata and controls

120 lines (85 loc) · 3.19 KB

PHP Managed constant models

Allow to declare constants with named attributes via standalone class model

Latest Stable Version Total Downloads Latest Unstable Version License

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist nick-denry/managed-constant-models

or add

"nick-denry/managed-constant-models": "^0.1.0"

to the require section of your composer.json file.

Usage

  1. Create managed constats model

    <?php
    
    namespace app\models;
    
    use nickdenry\managedConstants\interfaces\ManagedConstantInterface;
    use nickdenry\managedConstants\traits\ManagedConstantTrait;
    
    /**
    * TaskStatus constant model
    */
    class TaskStatus implements ManagedConstantInterface
    {
    
        use ManagedConstantTrait;
    
        const ACTIVE = 0;
        const DONE = 1;
        const _ATTRIBUTES = [
            self::ACTIVE => [
                'class' => 'task-active',
                'label' => 'Активна',
            ],
            self::DONE => [
                'class' => 'task-done',
                'label' => 'Завершена',
            ],
        ];
    
    }
  2. Use it with your another model class, i.e. yii2 model

    <?php
    
    namespace app\models;
    
    use app\models\TaskStatus;
    
    /**
    * This is the model class for table "task".
    *
    * @property int $id
    * @property string $title
    * @property int|null $created_at
    * @property int|null $updated_at
    */
    class Task extends \yii\db\ActiveRecord
    {
        ...
        /**
        * Get task statuses.
        */
        public static function getStatuses()
        {
            return new TaskStatus(); //TaskStatus()::class;
        }
        ...
    
    }

  1. Get constatns with the code

    <?php
    
    $constValue = Task::getStatuses()::ACTIVE; //$constValue = 0;
    
    Task::getStatuses()::ACTIVE; // ACTIVE constant;
    Task::getStatuses()::DONE; // DONE constant;
    Task::getStatuses()::constants(); // Returns array ['ACTIVE' => 0, 'DONE' => 1]
    Task::getStatuses()::values(); // Returns array [0, 1]
    Task::getStatuses()::listAttributes($constValue); // Returns array ['class' => 'task-active', 'label' => 'Активна']
    Task::getStatuses()::attribute($constValue, 'class'); // Returns 'task-active'
    
    Task::getStatuses()::getList(); 
    // Returns [
    //    ['id' => 0, 'class' => 'task-active', 'label' => 'Активна', ]
    //    ['id' => 1, 'class' => 'task-done', 'label' => 'Завершена', ],
    // ]