Basic Object Question

Hi,

I don’t know the correct english terms for this, so it’s hard to find the answer yet. I think it’s just a basic PHP Object thing, but it could also be something of Yii. So I want to give it a try.

I always thought that this two things are the same:




// 1

$test = new Product;

$test->category($id)->findAll();


// 2

Product::model()->category($id)->findAll();



Am I correct this is creating an instance of an class?

But this is not the same. I realize this, because I got an MySQL error. So I found that the thing that cause this, was that I call a scope ‘newest’ in a line above for a $dataProvider, like this:




$dataProvider=new CActiveDataProvider(Product::model()->newest(),array());


// This one gives me a MySQL error, because it includes the Order

// part (ORDER BY id DESC) of the newest() scope of the line above too so the error 

// is: Column 'id' in order clause is ambiguous.

print_r(Product::model()->category($id)->findAll());	


// But this one works, not including the newest() scope.

$test = new Product;

print_r($test->category($id)->findAll());	



The newest scope in my Product model:




	public function newest() 

	{

		$this->getDbCriteria()->mergeWith(array(

			'order' => 'id DESC',

			'offset'=>0,

		));

		return $this;

        }



Could someone explain this to me, or give me a hint what keywords I should look for? I guess it’s a very simple thing, but I just don’t get it :D .

update:

Yes I understand that I can fix it with:

Product::model()->[b]resetScope/b->category($id)->findAll();

or in the newest() scope (add t. ):




	public function newest() 

	{

		$this->getDbCriteria()->mergeWith(array(

			'order' => 't.id DESC',

			'offset'=>0,

		));

		return $this;

        }



But what I don’t understand is why the DbCriteria are still in the ‘memory’ when creating a new object. Or am I not creating a new object?

Ok, let me shorten the question.

When I do:




Product::model()->category($id)->findAll();



Why does it have a ‘memory’ for the scopes used previously?

And when I do:




$test = new Product;

$test->category($id)->findAll();



It won’t?

Product::model() creates Product class instance (so called singleton). So basically it is pretty similar to your $test->category($id)->findAll(), but you should not use it this way because model() function does slighly more:




new $className(null);

$model->attachBehaviors($model->behaviors());



so it creates model instance with "null" as constructor attribute which disables "scenario" handling for this object and then attaches behaviors.

Thanks a lot Red, this makes it a little better for me to understand. I also try to dig trough the Yii sourcecode to understand it more.

update: a by searching the singleton term, I found much more info (like http://stackoverflow.com/questions/20770742/does-yii-use-singleton). That was the term indeed!

I think I can work on from here. Thanks!