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 forum.silverstripe.org 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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Methods and where to put them


Go to End


3 Posts   686 Views

Avatar
MatthewW

Community Member, 7 Posts

4 February 2015 at 4:16pm

I have a couple of methods that are presentation-oriented, and I'm wondering the best place to put them. Currently, they're sitting in the model class. This works and makes them convenient to refer to in the template. However, I'm not so happy putting presentation code in the model. Does anybody have any suggestions about where best to put these methods? I thought perhaps a DataExtension might be a simple way to separate things out.

Here is a simple example:

	public function WebsitePrettyFormat() {
		return preg_replace ( 
			array("/^http:\/\//i","/\/$/"),
			array("",""),
			$this->Website
		);
	}

That's a minor case, but I have another much longer example where a method is generating all the markup for an image carousel, including the CSS and JS requirements.

Any suggestions?

Avatar
Pyromanik

Community Member, 419 Posts

5 February 2015 at 5:22am

The model is the place. It is a getter for information contained to that object.
If you were to have a ViewModel it would be tightly coupled to that class of model, and so also not very 'clean'.
You must remember that DataObject IS ViewableData (by extension - the concrete php subclass kind).

Depending on the situation a DataExtension can be a good idea - but again it applies at a class level (every instance, not specific ones), so effectively is the same thing (with a bit more overhead).

You could also apply an Extension to the DBField type that represents the data you're fetching. This way you can do something like $YoutubeCode.Embed
In this case here YoutubeCode would be embed code or perhaps just the video identifier, and Embed would be a function that comes from an extension you've applied to StringField (so both Varchar and Text would be acceptable as DB types, backed by a Text(area)Field in the CMS or something) which takes url/code and returns a full <iframe ... youtube video ... /...> embed thing.

There are also global template providers, but I don't think that would be applicable here as you're processing model instance specific data.

Avatar
MatthewW

Community Member, 7 Posts

5 February 2015 at 3:25pm

Cheers. Thanks for working through the options for me.