Property definition in the ActiveRecord

I am new to Yii2, so maybe I will ask something stupid, please be patient.

I’ve made my first ActiveRecord, and when I tried to get one record from database, sadly, my model has not populated. At stackoverflow, I guy pointed me out that I’ve defined the properties of my class what prevent yii to use the magic methods.

So I realized, I should not define the properties of the object like:

public $id;
public $username;
public $password;
...

First of all, I really do not like and do not use public fields, because this is against the immutable object principle.

But, why it is so painful, that I can not use autocomplete for my fields in my PHPStorm. Also the IDE is warn me that I did not defined the fields.

This is the right way to define an active record, without defining the fields?

Yes, do not define the properties that will be mapped from the database. For your IDE’s sake and autocompletion we usually do something like:

/**
 * MyModel
 *
 * @property int $id
 * @property string $name
 * @property int $status
 * @property int $created_at
 * @property int $updated_at
 */
class MyModel extends ActiveRecord
{
1 Like

I suggest you generate your AR Models with Gii.
That way you can speed up dev time and learn

1 Like