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, biapar, Willr, Ingo, simon_w

Access the model from the controller?


Reply


2 Posts   2073 Views

Avatar
UncleCheese

Forum Moderator, 4096 Posts

17 October 2008 at 10:19am

I have some pretty heavy functions that I've placed in my model class because I need them to be accessible through many interfaces on the site. But how can I call these functions from my controller class? Here's the best thing I can come up with:

public function myFunction()
{
$model_class = str_replace(get_class($this), "_Controller", "");
return DataObject::get_by_id($model_class,$this->ID)->myFunction($arg1, $arg2);
}

Ordinarily, I'd just call the function normally from the template, but the controller is used to parse data out of the url first, and then pass it to the model with $arg1, $arg2...

Does it have to be that ugly?

Avatar
François

25 Posts

21 November 2008 at 3:48am

Edited: 21/11/2008 3:48am

You can access a model method through the $this object in the controller. For me the following code works:

class Page extends SiteTree {
   public function MyModelMethod() {
      return $something;
   }
}

class Page_Controller extends ContentController {
   public function MyControllerMethod() {
      $v = $this->MyModelMethod();
   }
}