Easy management of Yii constants to obtain constants
I used a method to solve this problem.GetConstants ().
?
| 1234567891011121314 |
PublicstaticfunctiongetConstants ($ token, $ objectClass) {$ tokenLen = strlen ($ token); $ reflection = newReflectionClass ($ objectClass ); // php built-in $ allConstants = $ reflection-> getConstants (); // constants as array $ tokenConstants = array (); foreach ($ allConstantsas $ name => $ val) {if (substr ($ name, 0, $ tokenLen )! = $ Token) continue; $ tokenConstants [$ val] = $ val;} return $ tokenConstants ;} |
Usage example
To add this method to each ActiveRecord class, we can write a base class
| 1234567891011121314151617181920212223242526272829 |
ClassActiveRecordextendsCActiveRecord {/* Get class constants by token. if you set constants with same prefix, like: MY_STATUS_1 MY_STATUS_2 MY_STATUS_3, you can get it by calling Class: getConstants ('My); or Class :: getConstants ('My _ status'); */publicstaticfunctiongetConstants ($ token, $ objectClass) {$ tokenLen = strlen ($ token); $ reflection = newReflectionClass ($ objectClass ); // php built-in $ allConsta NT = $ reflection-> getConstants (); // constants as array $ tokenConstants = array (); foreach ($ allConstantsas $ name => $ val) {if (substr ($ name, 0, $ tokenLen )! = $ Token) continue; $ tokenConstants [$ val] = $ val;} return $ tokenConstants ;}} |
Then all model classes inherit this class instead of CActiveRecord.
| 12345678910 |
Optional {constTYPE_MUSIC = 'music'; constTYPE_VIDEO = 'Video'; constTYPE_DOC = 'document'; constSTATUS_ACTIVE = 'active'; constSTATUS_REMOVED = 'removed ';//...} |
Used outside model rules, methods, or modelsSelf: getConstants ()
| 1234567891011121314151617 |
ClassMediaextendsActiveRecord {//.. publicfunctionrules () {returnarray (array ('type', 'in', 'range' => self: getConstants ('Type _', __class __)),);}//.. publicstaticfunctiongetStatuses () {returnself: getConstants ('status _ ',__ CLASS _);} publicstaticfunctiongetTypes () {returnself: getConstants ('Type _', __class __);}} |
Other places
| 123 |
Print_r (Media: getConstants ('status _ ', 'media'); // or create Media method and use simplifiedprint_r (Media: getStatuses ()); |
Summary
Of course, if your model has only two constants, you can not use them, but we recommend that you use them when your model has a large number of constants.