CakeDC / Enum

Enumeration list for CakePHP
MIT License
27 stars 17 forks source link

Const Enum Type as integer #32

Closed lilHermit closed 7 years ago

lilHermit commented 7 years ago

I wonder if it would be possible to make the Const Type allow for integers as values. So for example:

class SampleTable extends Table {

    const TYPE_PLATFORM = 0;
    const TYPE_USER = 1;
    const TYPE_DEVICE = 2;

    public function initialize(array $config) {
        parent::initialize($config);

        $this->addBehavior('CakeDC/Enum.Enum', ['lists' => [
            'type' => [
                'strategy' => 'const',
                'prefix' => 'TYPE'
            ]
        ]]);
...

And show PLATFORM, USER and DEVICE in lists but put the integer in the db. I can get this working currently but its a bit hacky. I can add applicationRules => false and having array_flip($this->Samples->enum('type'))

Maybe I need to make a custom strategy? ;-)

pmoraes commented 7 years ago

Hi @lilHermit, if you want to put the integer in the database you need to create the constants in this way.

const TYPE_0 = 'PLATFORM'; const TYPE_1 = 'USER'; const TYPE_2 = 'DEVICE';

it will show the list using the names and the values will be the numbers.

do you have any question yet?

lilHermit commented 7 years ago

@pmoraes Yeah that doesn't help because I want the constants to be meaningful so I can use them in queries.

$query->conditions(['type' => SampleTable::TYPE_PLATFORM]);

I'll go with the hacky approach but if I need it again I might look at writing a "Strategy"

inoas commented 7 years ago

But where is it hacky? That's how PHP constants work. We do not have atoms/symbols in PHP, sadly.

You can of course do:

    const TYPE_PLATFORM = 'TYPE_PLATFORM';
    const TYPE_USER = 'TYPE_USER';
    const TYPE_DEVICE = 'TYPE_DEVICE;

... then 'type' => SampleTable::TYPE_PLATFORM should work.

And then at some point do some po file translation, if required.

lilHermit commented 7 years ago

@inoas I think disabling applicationRules and using array_flip is a bit hacky personally.

I want to have an integer in the db for query/index speed.

No problem thanks for your time.

pmoraes commented 7 years ago

Hi @lilHermit for this case, you'll need to create a custom strategy, because we use the const name without the prefix to put in the option value and the const value to show in the list. So we don't have any strategy to work as you want. I suggest you to create new strategy than this work around.

Let us know if you need some more help about this issue.

Thanks, Peter Moraes.

lilHermit commented 7 years ago

The solution was quite simple for integer constants

https://bitbucket.org/snippets/lilHermit/onaLe

It would be easy to add a config option to the ConstStrategy for integers, which adds this array_flip if other users request it.

Also as the validation callback uses the enum method this fixes the Application rules issue too.