rthriller Posted September 9, 2013 Share Posted September 9, 2013 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 More sharing options...
Edward Posted September 10, 2013 Share Posted September 10, 2013 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. 1 Link to comment Share on other sites More sharing options...
Edward Posted September 10, 2013 Share Posted September 10, 2013 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 More sharing options...
Larry Posted September 11, 2013 Share Posted September 11, 2013 I think Edward's first answer is on the money (thanks, Edward). By making the model() method static, you can use lots of non-static methods through it. Link to comment Share on other sites More sharing options...
Recommended Posts