Jump to content
Larry Ullman's Book Forums

Static Class Instance. Why?


rthriller
 Share

Recommended Posts

Hello,

 

Reading chapter 7 (page 136), I understand what static instance (and method) are but what I didn't understand is : Why is the findByPK a non-static method.

 

If findByPK was static then simply we get :

$model = Page::findByPk();

I know findByPK was generated by gii, my question is not 100% related to this book content but to yii philosophy and design.

 

Thanks.

Link to comment
Share on other sites

You can't do what you are doing above, you do need an instance of the Page model to access that non static method findByPk which is located in CActiveRecord.

 

If you take a look at CActiveRecord which Page Class is an extension of you will find this method

	* @param string $className active record class name.
* @return CActiveRecord active record model instance.
*/
public static function model($className=__CLASS__)
{
if(isset(self::$_models[$className]))
return self::$_models[$className];
else
{
$model=self::$_models[$className]=new $className(null);
$model->attachBehaviors($model->behaviors());
return $model;
}
}

You can see that the model method is a static method and therefore to use findByPk you must first run this from Page Class to get an instance.

 

Then you can do the following by some extra chaining.

$model = Page::model()->findByPk($id);

I hope i am making some sense here.

  • Upvote 1
Link to comment
Share on other sites

I think you need to email Qiang Xue to ask him why he designed it this way.

 

https://github.com/qiangxue

 

In the CActiveRecord documents they state this:

 

"CActiveRecord is the base class for classes representing relational data.

It implements the active record design pattern, a popular Object-Relational Mapping (ORM) technique. Please check the Guide for more details about this class."

 

So maybe you need to look more into the design pattern Object-Relational Mapping ORM to find your answer. The functions also in findByPk also requires some instantated functions in order to work.

Link to comment
Share on other sites

 Share

×
×
  • Create New...