Reputation: 813
I have a couple of generic functions that i use across multiple different pages and DataObjects. I'm trying to figure out the best place to store these. Currently I have them in Page.php but as they don't apply to all pages, I would like to move and store them in classes in a sub folder of the mysite/code called helpers. This will also help the next developers to locate and update these classes if need be. (I am OK with leaving it in the Page.php class if that is the way it is done in silverstripe)
<?php
public class GetPublishedArticles {
public function GetAllPublishedArticlesByType($class){
error_log('Hit GPA',0);
$pages = $class::get();//->filter(array('Published'=>1));
if($pages->count()){
return $pages;
}
else{
return false;
}
}
}
Template:
<% loop GetAllPublishedArticlesByType('Page') %>
$Link
<% end_loop %>
Things I have tried.
So how can i make use of this re-usable code? Adding it to the page works, but might make it difficult for other developers to locate if they are trying to change.
Upvotes: 1
Views: 73
Reputation: 1592
From the template point of view, the function is defined on
To make some functions available on different pages, but keep DRY principle, you should define them as extension, and declare extension for selected page types.
class PublishedArticlesController extends Extension {
// define your methods
}
# in mysite/_config/config.yml
ArticlePage_Controller:
extensions:
- PublishedArticlesController
Upvotes: 3