yii-gii icon indicating copy to clipboard operation
yii-gii copied to clipboard

Simple property mapper for ActiveRecord.

Open mj4444ru opened this issue 4 years ago • 7 comments

It would be great if the generated ActiveRecord had a property mapper. That is, create_at was mapped to createAt. For example like this:

public function getAttributeMap(): array
{
    return [
        'createAt' => 'create_at',
    ];
}

public function __get(string $name)
{
    return parent::__get($this->getAttributeMap()[$name] ?? $name);
}

public function __set(string $name, $value): void
{
    parent::__set($this->getAttributeMap()[$name] ?? $name, $value);
}

public function __isset(string $name): bool
{
    return parent::__isset($this->getAttributeMap()[$name] ?? $name);
}

public function __unset(string $name): void
{
    return parent::__unset($this->getAttributeMap()[$name] ?? $name);
}

@property will be appropriate.

mj4444ru avatar Oct 20 '20 00:10 mj4444ru

How would that look like in queries? Would real field name be used or an alias that we have defined?

samdark avatar Oct 21 '20 23:10 samdark

This improvement only affects magical properties. When working with properties through functions, we continue to work with real names.

For example, we have a create_at property in the database table. When the class is generated, the getAttributeMap method is generated. and a property declaration like:

/**
 * @property int $createAt
 */

we can access the property like this:

$time = $model->getAttribute('create_at');
$time = $model->createAt;
$time = $model->create_at;

The editor will prompt us $model->createAt. It looks better.

mj4444ru avatar Oct 22 '20 16:10 mj4444ru

While it looks better, it's not convenient when you have createAt in code but create_at in query conditions in the same code.

samdark avatar Oct 24 '20 10:10 samdark

While it looks better, it's not convenient when you have createAt in code but create_at in query conditions in the same code.

  1. If in your project all properties are converted in this way, you perfectly understand where and what to expect.
  2. These are different levels of abstraction.
  3. Do ORM users have such problems?

mj4444ru avatar Oct 24 '20 20:10 mj4444ru

  1. Depends on the ORM. Doctrine has a special DQL query language that allows you to use mapped properties in conditions so you have same names everywhere but that comes with its own set of drawbacks.

samdark avatar Oct 24 '20 21:10 samdark

In any case, it is not difficult, and I have no doubt that many will like it. This can also be made optional.

mj4444ru avatar Oct 25 '20 19:10 mj4444ru

Alright. Having an option to generate these is fine.

samdark avatar Oct 29 '20 10:10 samdark