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.

We've moved the forum!

Please use for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Archive /

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

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

Access the model from the controller?

Go to End

2 Posts   3916 Views


Forum Moderator, 4102 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?


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