Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Archive /

Our old forums are still available as a read-only archive.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo

How to reference Model methods from Controler?


Go to End
Reply


3 Posts   2048 Views

Avatar
TomDude48

Community Member, 2 Posts

29 February 2008 at 6:27am

I have found myself duplicating methods in a Model and its related Controler.
E.g.

Blog extends Page() {
function Posts($numPerPage) {
return DataObject::get("Post","BlogID=$this->ID","","",(int)$_GET['start'] . ", $numPerPage"");
}
}

Blog_Controller extends Page_Controller() {
function Posts() {
return DataObject::get("Post","BlogID=$this->ID","","",(int)$_GET['start'] . ", 8");
}
}

I was looking for a way to just use the function in the Model class and noticed that model class functions are inherited automatically,

E.g. just remove the Post function from the controler and the $this->Post() will call the function in the Model. However, parent does not seem to work like it does with other functions such as init().

E.g. the below call to parent::Posts() does not work, but parent::init() does work.

Blog_Controller extends Page_Controller() {
function init() {
parent::init();
}

function Posts($id) {
parent::Posts(8);
}
}

Any ideas on how to refernce the model function when you have a function with the same name in the controller?

Avatar
Sean

Forum Moderator, 922 Posts

1 March 2008 at 3:26pm

Good question, I do know that if you have a method on the controller, and if you reference a DB field, or relation by calling $this->Field() (replace Field with your DB field name) then it works. However, I'm not sure if you can call a method on the model the same way (not a DB field).

Does this example work, perhaps?

class Page extends SiteTree {

   function Posts() {
      return 'Lots of posts!';
   }

}

class Page_Controller extends ContentController {

   function Posts() {
      return $this->Posts();
   }

}

Cheers,
Sean

Avatar
Fuzz10

Community Member, 787 Posts

5 March 2008 at 1:15am

<subscribe to thread>