underscore and camelCase interchangeable in Yii?

Hi, I’m really new to Yii. I was just wondering if using this_style and thisStyle really matters to Yii when referring to AR attributes. For example, how come I can write:


        $newProject=new Project;

        $newProjectName = 'Test Project Creation';

        $newProject->setAttributes(array(

                'name' => $newProjectName,

                'description' => 'This is a test for new project creation',

                'createTime' => '2009-09-09 00:00:00',

                'createUser' => '1',

                'updateTime' => '2009-09-09 00:00:00',

                'updateUser' => '1',

            )

        );

When the table columns are actually using underscores. (see snippet from fixture below) I’m kinda confused. Is Yii doing something automagically for me?


'project1'=>array(

        'name' => 'Test Project 1',

        'description' => 'This is test project 1',

        'create_time' => '',

        'create_user_id' => '',

        'update_time' => '',

        'update_user_id' => '',

    ),

I assume that it is not throwing an error as you are using the setAttributes method.

Please review the following code:




public function setAttributes($values,$safeOnly=true)

	{

		if(!is_array($values))

			return;

		$attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());

		foreach($values as $name=>$value)

		{

			if(isset($attributes[$name]))  // <--- checks for attribute

				$this->$name=$value; // <--- if exists then set, nothing happens if doesnt exists

			else if($safeOnly)

				$this->onUnsafeAttribute($name,$value);

		}

	}



If you try to set the values using __set, __get from CComponent, then it will throw an error




// This is ok as update_time exists

$model->update_time = '2009-09-09 00:00:00';


// This will throw an error if table column is update_time

$model->updateTime = '2009-09-09 00:00:00';



Is there a way to map table column names to properties? Yii suggests to name variables with camelCase while most sources (including Yii’s blog tutorial) suggest to name columns in tables lowercase with underscores only. The main point seems to be maximizing compatibility across various systems.

I prefer to stick to these conventions, but haven’t found a way of mapping properties to column names yet.

As chiefsucker already mentions, I agree it’s quite inconsistent in Yii.

Looking at the Yii convention page under 2. Code it says:

Under 6. Database it says:

However column names in the database like [font="Courier New"]department_manager[/font] (like the convention tells us) will convert to a model field name [font="Courier New"]department_manager[/font] instead of [font="Courier New"]departmentManager[/font] (preferred by the convention).

It would be really nice if Yii’s [font=“Courier New”]__get[/font] and [font=“Courier New”]__set[/font] methods of [font=“Courier New”]CActiveRecord[/font] would transform names like [font=“Courier New”]department_manager[/font] to [font=“Courier New”]departmentManager[/font].

Cool. thanks for your replies guys. :)

I’m really a configuration guy, but yii looked really interesting.

anyway, i went back to what i know (codeigniter). it’s not as well designed imo, but hey projects have deadlines. Might study again when i have time.

I second this! In the meantime I suggest the documentation be revised so that it is not inconsistent.

Sorry to bounce an old thread but yeah I’m confused, what is the deal with this?

I camelCased my DB names because I care more about my PHP objects that my database, but then when doing a relation ($model->users) Yii seemed to be looking for user_id rather than userId despite my relations saying:


    public function relations()

    {

        return array(

            'user' => array(self::BELONGS_TO, 'User', 'userId'), 

        );

    }

So what IS the recommended way of naming db columns etc? Or is there not a convention for this?

cheers!

Lowercase singular. :)

Underscore as word-delimiter, or lowercaseCamel for composite words (userId maps to user_id)

Does Yii map underscores to camelCasing?

With a database column of login_provider, I get “HaLogins.loginProvider is not defined” if I camelCase the property name in PHP. i.e. $model->loginProvider = ‘blah’

No.

The easiest way is to use camelCase in the names of DB fields.

Or you can find/write behavior that adds mapping. But I’m not sure you can cover all use cases.

It does.

If you have a table called model_manager Gii will map it to ModelManager.

Hello, jacmoe

It would not do so for table attributes.

This naming convention thing is bugging me to no end:

say i have to now declare a custom field in my model, how should i do it

case1) use camelcase:


function getFullName() {...}

and then use it in gridView mixing different cases:


'columns'=>array('user_id', 'fullName')

OR

case2) use lowercase underscore which leads to ridiculous method name:


function getFull_name() {...}

but i can use it in gridView and it wont look differen there:


'columns'=>array('user_id', 'full_name')

neither looks clean to me.

I agree that we should have a way to set default setting for member variables. Whether they are camelCased or something_else. I would prefer the first one.

In my opinion camel case for variables is awful, I will always use lower case/underscore, with one exception: If the variable represents a class name, then camel case is fine as that helps me to instantly recognise it as such, but otherwise, no. I think that the code then is far more readable.

For database columns, always lower case/underscore. I think that anything else is just looking for bugs.

Classes and methods, the Yii convention is good - instantly recognisable.

As a long-time database guy, I’ve done camelCase and underscore. I’ve come to prefer underscore and I think that’s becoming more standard (as of 2017).