Jump to:

17452 Posts in 4473 Topics by 1971 members


SilverStripe Forums » Archive » Access the model from the controller?

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

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

Page: 1
Go to End
Author Topic: 1997 Views
  • UncleCheese
    4085 Posts

    Access the model from the controller? Link to this post

    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?

  • François
    25 Posts

    Re: Access the model from the controller? Link to this post

    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();

Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.