Yii Framework Forum: Where to add helper classes of model values? - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Where to add helper classes of model values?

#1 User is offline   blaces 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 137
  • Joined: 06-April 12

Posted 04 August 2016 - 10:19 AM

Hi.

I do not know what is the buzz word for the following problem.

For example:
I have a model class, which has a 'gender' property. This 'gender' property values are integer 1 and 2 (or 3).
/**
 * This is the model class for table "{{example_model}}"
 * @property integer $gender
 */
class ExampleModel extends ActiveRecord 
{
}


I have another class, it is called for instance: 'ModelHelper' which has a static function to map the 'gender' property value to labels in the View file.:
<?php

class ModelHelper
{
    public static getGenderList()
    {
        return [1 => Yii::t('app', 'Male'), 2 => Yii:t('app', 'Female'), 3 => Yii:t('app', 'Other')];
    }
    
}


This is used only in the View file for a 'Dropdown list':

    <?= $form->field($model, 'gender')->dropDownList(ModelHelper::getGenderList(), ['prompt' => Yii::t('app', 'SelectGender')]) ?>


What is your suggestions, where should I place this ModelHelper class?

I do not want to extend the original Model class, because in my view this is other kind of logic, which should be store in a seperated class.
I can place into the 'components', but there are behaviours, object, components classes too...
0

#2 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,184
  • Joined: 17-January 09
  • Location:Russia

Posted 04 August 2016 - 01:51 PM

I'd name it Gender and put into \app\enums:

class Gender
{
    const MALE = 'male';
    const FEMALE = 'female';

    public static function list()
    {
         return [
             null => 'Unknown',
             self::MALE => 'Male',
             self::FEMALE => 'Female',
         ];
    }
}

$myGender = Gender::MALE;

Yii 2.0 Development Cookbook

Enjoying Yii? Star us at github

Support me so I can work more on Yii: https://www.patreon.com/samdark
1

#3 User is offline   blaces 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 137
  • Joined: 06-April 12

Posted 05 August 2016 - 01:45 PM

This is a nice solution.
In PHP environment I totally forget the ENUMs.

I thought on the 'component/extension/' like in the ASP.NET. To extend the 'Model/ActiveRecord' class with these functions.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users