MINOR Updated coding conventions to require the 'public' keyword for class methods and variables

This commit is contained in:
Ingo Schommer 2012-01-30 23:13:42 +01:00
parent 008ecf750a
commit 04a10a4265
41 changed files with 156 additions and 152 deletions

View File

@ -70,11 +70,11 @@ You can have more customized logic and interface feedback through a custom contr
class MyController extends Controller { class MyController extends Controller {
protected $template = "BlankPage"; protected $template = "BlankPage";
function Link($action = null) { public function Link($action = null) {
return Controller::join_links('MyController', $action); return Controller::join_links('MyController', $action);
} }
function Form() { public function Form() {
$form = new Form( $form = new Form(
$this, $this,
'Form', 'Form',
@ -89,7 +89,7 @@ You can have more customized logic and interface feedback through a custom contr
return $form; return $form;
} }
function doUpload($data, $form) { public function doUpload($data, $form) {
$loader = new CsvBulkLoader('MyDataObject'); $loader = new CsvBulkLoader('MyDataObject');
$results = $loader->load($_FILES['CsvFile']['tmp_name']); $results = $loader->load($_FILES['CsvFile']['tmp_name']);
$messages = array(); $messages = array();
@ -177,13 +177,13 @@ Sample implementation of a custom loader. Assumes a CSV-file in a certain format
'callback' => 'getTeamByTitle' 'callback' => 'getTeamByTitle'
) )
); );
static function importFirstAndLastName(&$obj, $val, $record) { public static function importFirstAndLastName(&$obj, $val, $record) {
$parts = explode(' ', $val); $parts = explode(' ', $val);
if(count($parts) != 2) return false; if(count($parts) != 2) return false;
$obj->FirstName = $parts[0]; $obj->FirstName = $parts[0];
$obj->LastName = $parts[1]; $obj->LastName = $parts[1];
} }
static function getTeamByTitle(&$obj, $val, $record) { public static function getTeamByTitle(&$obj, $val, $record) {
$SQL_val = Convert::raw2sql($val); $SQL_val = Convert::raw2sql($val);
return DataObject::get_one( return DataObject::get_one(
'FootballTeam', "Title = '{$SQL_val}'" 'FootballTeam', "Title = '{$SQL_val}'"

View File

@ -85,10 +85,10 @@ Create a new file called `zzz_admin/code/BookmarkedPageExtension.php` and insert
:::php :::php
<?php <?php
class BookmarkedPageExtension extends DataExtension { class BookmarkedPageExtension extends DataExtension {
function extraStatics() { public function extraStatics() {
return array('db' => array('IsBookmarked' => 'Boolean')); return array('db' => array('IsBookmarked' => 'Boolean'));
} }
function updateCMSFields(&$fields) { public function updateCMSFields(&$fields) {
$fields->addFieldToTab('Root.Main', $fields->addFieldToTab('Root.Main',
new CheckboxField('IsBookmarked', "Show in CMS bookmarks?") new CheckboxField('IsBookmarked', "Show in CMS bookmarks?")
); );
@ -114,7 +114,7 @@ Add the following code to a new file `zzz_admin/code/BookmarkedLeftAndMainExtens
:::php :::php
<?php <?php
class BookmarkedPagesLeftAndMainExtension extends LeftAndMainExtension { class BookmarkedPagesLeftAndMainExtension extends LeftAndMainExtension {
function BookmarkedPages() { public function BookmarkedPages() {
return DataList::create('Page')->where('"IsBookmarked" = 1'); return DataList::create('Page')->where('"IsBookmarked" = 1');
} }
} }

View File

@ -48,7 +48,7 @@ Successive capitalized letters are not allowed, e.g. a class `XMLImporter` is no
Static methods should be in `lowercase_with_underscores()` format: Static methods should be in `lowercase_with_underscores()` format:
:::php :::php
static function my_static_method() {} public static function my_static_method() {}
Action handlers on controllers should be in `completelylowercase()` format. Action handlers on controllers should be in `completelylowercase()` format.
This is because they go into the controller URL in the same format (eg, `home/successfullyinstalled`). This is because they go into the controller URL in the same format (eg, `home/successfullyinstalled`).
@ -56,7 +56,7 @@ Method names are allowed to contain underscores here, in order to allow URL part
(`mypage\my-action` gets translated to `my_action()` automatically). (`mypage\my-action` gets translated to `my_action()` automatically).
:::php :::php
function mycontrolleraction() {} public function mycontrolleraction() {}
Object methods that will be callable from templates should be in `$this->UpperCamelCase()` format. Object methods that will be callable from templates should be in `$this->UpperCamelCase()` format.
Alternatively, `$this->getUpperCamelCase()` will work the same way in templates - Alternatively, `$this->getUpperCamelCase()` will work the same way in templates -
@ -65,7 +65,9 @@ you can access both coding styles as `$UpperCamelCase`.
Other instance methods should be in `$this->lowerCamelCase()` format: Other instance methods should be in `$this->lowerCamelCase()` format:
:::php :::php
function myInstanceMethod() {} public function myInstanceMethod() {}
Methods inside classes must always declare their visibility by using one of the private, protected, or public modifiers.
### Variables ### Variables
@ -74,10 +76,12 @@ Static variables should be `self::$lowercase_with_underscores`
:::php :::php
self::$my_static_variable = 'foo'; self::$my_static_variable = 'foo';
Object variables should be `$this->lowerCamelCase` Member variables should be `$this->lowerCamelCase`
:::php :::php
$this->myObjectVariable = 'foo'; $this->myMemberVariable = 'foo';
Member variables always declare their visibility by using one of the private, protected, or public modifiers
### Constants ### Constants
@ -232,20 +236,20 @@ No method or function invocation is allowed to have spaces directly
before or after the opening parathesis, as well as no space before the closing parenthesis. before or after the opening parathesis, as well as no space before the closing parenthesis.
:::php :::php
function foo($arg1, $arg2) {} // good public function foo($arg1, $arg2) {} // good
function foo ( $arg1, $arg2 ) {} // bad public function foo ( $arg1, $arg2 ) {} // bad
Keep the opening brace on the same line as the statement. Keep the opening brace on the same line as the statement.
:::php :::php
// good // good
function foo() { public function foo() {
// ... // ...
} }
:::php :::php
// bad // bad
function bar() public function bar()
{ {
// ... // ...
} }
@ -346,7 +350,7 @@ Try to avoid using PHP's ability to mix HTML into the code.
:::php :::php
// PHP code // PHP code
function getTitle() { public function getTitle() {
return "<h2>Bad Example</h2>"; return "<h2>Bad Example</h2>";
} }
@ -357,7 +361,7 @@ Better: Keep HTML in template files:
:::php :::php
// PHP code // PHP code
function getTitle() { public function getTitle() {
return "Better Example"; return "Better Example";
} }
@ -410,7 +414,7 @@ Example:
Put code into the classes in the following order (where applicable). Put code into the classes in the following order (where applicable).
* Static variables * Static variables
* Object variables * Member variables
* Static methods * Static methods
* Data-model definition static variables. (`$db`, `$has_one`, `$many_many`, etc) * Data-model definition static variables. (`$db`, `$has_one`, `$many_many`, etc)
* Commonly used methods like `getCMSFields()` * Commonly used methods like `getCMSFields()`

View File

@ -107,7 +107,7 @@ Here's an example for replacing `Director::isDev()` with a (theoretical) `Env::i
* Returns true if your are in development mode * Returns true if your are in development mode
* @deprecated (since 2.2.2) Use {@link Env::is_dev()} instead. * @deprecated (since 2.2.2) Use {@link Env::is_dev()} instead.
*/ */
function isDev() { public function isDev() {
user_error("DEPRECATED: Use Env::is_dev() instead.", E_USER_NOTICE); user_error("DEPRECATED: Use Env::is_dev() instead.", E_USER_NOTICE);
return Env::is_dev(); return Env::is_dev();
} }

View File

@ -76,7 +76,7 @@ Example for PHP:
:::php :::php
class Page extends SiteTree { class Page extends SiteTree {
function myFunction() { public function myFunction() {
// ... // ...
} }
} }

View File

@ -52,7 +52,7 @@ The function should return a map where the keys are the names of the static vari
:::php :::php
class CustomMember extends DataExtension { class CustomMember extends DataExtension {
function extraStatics() { public function extraStatics() {
return array( return array(
'db' => array( 'db' => array(
'AvatarURL' => 'Varchar', 'AvatarURL' => 'Varchar',
@ -161,7 +161,7 @@ extended by.
class CustomerWorkflow extends DataExtension { class CustomerWorkflow extends DataExtension {
function IsMarkedForDeletion() { public function IsMarkedForDeletion() {
return ($this->owner->Account()->IsMarkedForDeletion == 1) ? true : false; return ($this->owner->Account()->IsMarkedForDeletion == 1) ? true : false;
} }

View File

@ -17,7 +17,7 @@ which returns a `[api:FieldList]`''.
:::php :::php
class MyPage extends Page { class MyPage extends Page {
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty')); $fields->addFieldToTab('Root.Content',new CheckboxField('CustomProperty'));
return $fields; return $fields;

View File

@ -64,7 +64,7 @@ This will add an object with ID 12 to the cart.
When you create a function, you can access the ID like this: When you create a function, you can access the ID like this:
:::php :::php
function addToCart ($request) { public function addToCart ($request) {
$param = $r->allParams(); $param = $r->allParams();
echo "my ID = ".$param["ID"]; echo "my ID = ".$param["ID"];
$obj = DataObject::get("myProduct", $param["ID"]); $obj = DataObject::get("myProduct", $param["ID"]);
@ -83,7 +83,7 @@ You can access the following controller-method with /team/signup
class Team extends DataObject {} class Team extends DataObject {}
class Team_Controller extends Controller { class Team_Controller extends Controller {
function signup($id, $otherId) { public function signup($id, $otherId) {
return $this->renderWith('MyTemplate'); return $this->renderWith('MyTemplate');
} }
} }

View File

@ -59,7 +59,7 @@ You can also create your own functions by extending the image class, for example
return $this->getWidth() < $this->getHeight(); return $this->getWidth() < $this->getHeight();
} }
function generatePaddedImageByWidth(GD $gd,$width=600,$color="fff"){ public function generatePaddedImageByWidth(GD $gd,$width=600,$color="fff"){
return $gd->paddedResize($width, round($gd->getHeight()/($gd->getWidth()/$width),0),$color); return $gd->paddedResize($width, round($gd->getHeight()/($gd->getWidth()/$width),0),$color);
} }

View File

@ -63,12 +63,12 @@ Note that if you want to look this class-name up, you can call Object::getCustom
## Overloading getCMSFields() ## Overloading getCMSFields()
If you overload the built-in function getCMSFields(), then you can change the form that is used to view & edit member If you overload the built-in public function getCMSFields(), then you can change the form that is used to view & edit member
details in the newsletter system. This function returns a `[api:FieldList]` object. You should generally start by calling details in the newsletter system. This function returns a `[api:FieldList]` object. You should generally start by calling
parent::getCMSFields() and manipulate the `[api:FieldList]` from there. parent::getCMSFields() and manipulate the `[api:FieldList]` from there.
:::php :::php
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->insertBefore(new TextField("Age"), "HTMLEmail"); $fields->insertBefore(new TextField("Age"), "HTMLEmail");
$fields->removeByName("JobTitle"); $fields->removeByName("JobTitle");
@ -106,18 +106,18 @@ things, you should add appropriate `[api:Permission::checkMember()]` calls to th
* Modify the field set to be displayed in the CMS detail pop-up * Modify the field set to be displayed in the CMS detail pop-up
*/ */
function updateCMSFields(FieldList $currentFields) { public function updateCMSFields(FieldList $currentFields) {
// Only show the additional fields on an appropriate kind of use // Only show the additional fields on an appropriate kind of use
if(Permission::checkMember($this->owner->ID, "VIEW_FORUM")) { if(Permission::checkMember($this->owner->ID, "VIEW_FORUM")) {
// Edit the FieldList passed, adding or removing fields as necessary // Edit the FieldList passed, adding or removing fields as necessary
} }
} }
function extraStatics() { public function extraStatics() {
// Return an array containing keys 'db', 'has_one', 'many_many', 'belongs_many_many', // Return an array containing keys 'db', 'has_one', 'many_many', 'belongs_many_many',
} }
function somethingElse() { public function somethingElse() {
// You can add any other methods you like, which you can call directly on the member object. // You can add any other methods you like, which you can call directly on the member object.
} }
} }

View File

@ -84,7 +84,7 @@ That last example is a bit large, and is complicating our template up with icky
logic into the controller logic into the controller
:::php :::php
function FavouriteCacheKey() { public function FavouriteCacheKey() {
$member = Member::currentUser(); $member = Member::currentUser();
return implode('_', array( return implode('_', array(
'favourites', 'favourites',
@ -122,7 +122,7 @@ which will invalidate after the cache lifetime expires. If you need more control
configurable only on a site-wide basis), you could add a special function to your controller: configurable only on a site-wide basis), you could add a special function to your controller:
:::php :::php
function BlogStatisticsCounter() { public function BlogStatisticsCounter() {
return (int)(time() / 60 / 5); // Returns a new number every five minutes return (int)(time() / 60 / 5); // Returns a new number every five minutes
} }

View File

@ -28,11 +28,11 @@ map of permission code names with a human readable explanation of its purpose (s
:::php :::php
class Page_Controller implements PermissionProvider { class Page_Controller implements PermissionProvider {
function init() { public function init() {
if(!Permission::check("VIEW_SITE")) Security::permissionFailure(); if(!Permission::check("VIEW_SITE")) Security::permissionFailure();
} }
function providePermissions() { public function providePermissions() {
return array( return array(
"VIEW_SITE" => "Access the site", "VIEW_SITE" => "Access the site",
); );

View File

@ -30,7 +30,7 @@ RestfulService (see [flickrservice](http://silverstripe.org/flickr-module/) and
//example for extending RestfulService //example for extending RestfulService
class FlickrService extends RestfulService { class FlickrService extends RestfulService {
function __construct($expiry=NULL){ public function __construct($expiry=NULL){
parent::__construct('http://www.flickr.com/services/rest/', $expiry); parent::__construct('http://www.flickr.com/services/rest/', $expiry);
$this->checkErrors = true; $this->checkErrors = true;
} }
@ -121,7 +121,7 @@ could delgate the error handling to it's descendant class. To handle the errors
This will raise Youtube API specific error messages (if any). This will raise Youtube API specific error messages (if any).
*/ */
function errorCatch($response){ public function errorCatch($response){
$err_msg = $response; $err_msg = $response;
if(strpos($err_msg, '<') === false) if(strpos($err_msg, '<') === false)
//user_error("YouTube Service Error : $err_msg", E_USER_ERROR); //user_error("YouTube Service Error : $err_msg", E_USER_ERROR);
@ -135,7 +135,7 @@ could delgate the error handling to it's descendant class. To handle the errors
If you want to bypass error handling on your sub-classes you could define that in the constructor. If you want to bypass error handling on your sub-classes you could define that in the constructor.
:::php :::php
function __construct($expiry=NULL){ public function __construct($expiry=NULL){
parent::__construct('http://www.flickr.com/services/rest/', $expiry); parent::__construct('http://www.flickr.com/services/rest/', $expiry);
$this->checkErrors = false; //Set checkErrors to false to bypass error checking $this->checkErrors = false; //Set checkErrors to false to bypass error checking
} }
@ -152,7 +152,7 @@ Put something like this code in mysite/code/Page.php inside class Page_Controlle
:::php :::php
// Accepts an RSS feed URL and outputs a list of links from it // Accepts an RSS feed URL and outputs a list of links from it
function RestfulLinks($url){ public function RestfulLinks($url){
$delicious = new RestfulService($url); $delicious = new RestfulService($url);
$conn = $delicious->connect(); $conn = $delicious->connect();

View File

@ -17,12 +17,12 @@ your website, so its advisable to just create feeds from subclasses of `[api:Sit
* The second part sets up /this-page/rss to return the RSS feed. This one returns the children of the current page. * The second part sets up /this-page/rss to return the RSS feed. This one returns the children of the current page.
:::php :::php
function init() { public function init() {
RSSFeed::linkToFeed($this->Link() . "rss", "RSS feed of this blog"); RSSFeed::linkToFeed($this->Link() . "rss", "RSS feed of this blog");
parent::init(); parent::init();
} }
function rss() { public function rss() {
$rss = new RSSFeed($this->Children(), $this->Link(), "My feed", "This is an example feed.", "Title", "Content", "Author"); $rss = new RSSFeed($this->Children(), $this->Link(), "My feed", "This is an example feed.", "Title", "Content", "Author");
$rss->outputToBrowser(); $rss->outputToBrowser();
} }
@ -45,17 +45,17 @@ something like this:
class Page_Controller extends ContentController { class Page_Controller extends ContentController {
function init() { public function init() {
RSSFeed::linkToFeed($this->Link() . "rss", "10 Most Recently Updated Pages"); RSSFeed::linkToFeed($this->Link() . "rss", "10 Most Recently Updated Pages");
parent::init(); parent::init();
} }
function rss() { public function rss() {
$rss = new RSSFeed($this->LatestUpdates(), $this->Link(), "10 Most Recently Updated Pages", "Shows a list of the 10 most recently updated pages.", "Title", "Content", "Author"); $rss = new RSSFeed($this->LatestUpdates(), $this->Link(), "10 Most Recently Updated Pages", "Shows a list of the 10 most recently updated pages.", "Title", "Content", "Author");
$rss->outputToBrowser(); $rss->outputToBrowser();
} }
function LatestUpdates() { public function LatestUpdates() {
// 10 is the number of pages // 10 is the number of pages
return DataObject::get("Page", "", "LastEdited DESC", "", 10); return DataObject::get("Page", "", "LastEdited DESC", "", 10);
} }

View File

@ -30,13 +30,13 @@ CustomSideReport.php
:::php :::php
<?php <?php
class CustomSideReport_NameOfReport extends SideReport { class CustomSideReport_NameOfReport extends SideReport {
function title() { public function title() {
// the name of our report // the name of our report
} }
function records() { public function records() {
// what we want the report to return and what order // what we want the report to return and what order
} }
function fieldsToShow() { public function fieldsToShow() {
// which fields on that object do we want to show? Title, Author? // which fields on that object do we want to show? Title, Author?
} }
} }
@ -57,17 +57,17 @@ CustomSideReport.php
* of type Page. Sorted by title. * of type Page. Sorted by title.
*/ */
class CustomSideReport_AllPages extends SideReport { class CustomSideReport_AllPages extends SideReport {
function title() { public function title() {
// this is the title of the report // this is the title of the report
return "All Pages"; return "All Pages";
} }
function records() { public function records() {
// the data the report returns all the dataobjects of type Page and sorted by title. See datamodel for more info // the data the report returns all the dataobjects of type Page and sorted by title. See datamodel for more info
return DataObject::get("Page", "", "Title"); return DataObject::get("Page", "", "Title");
} }
function fieldsToShow() { public function fieldsToShow() {
// fields you want to display. This will display a list of titles which link to the page in the cms. Handy! // fields you want to display. This will display a list of titles which link to the page in the cms. Handy!
return array( return array(
"Title" => array("NestedTitle", array("2")), "Title" => array("NestedTitle", array("2")),

View File

@ -39,7 +39,7 @@ Create a mysite/code/CustomSiteConfig.php file.
class CustomSiteConfig extends DataExtension { class CustomSiteConfig extends DataExtension {
function extraStatics() { public function extraStatics() {
return array( return array(
'db' => array( 'db' => array(
'FooterContent' => 'HTMLText' 'FooterContent' => 'HTMLText'

View File

@ -134,7 +134,7 @@ it is a good starting point, for choosing your customisation.
return false; return false;
} }
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
return $fields; return $fields;
} }
@ -187,16 +187,16 @@ Example:
static $many_many = array( static $many_many = array(
'MyProducts' => 'MyProduct' 'MyProducts' => 'MyProduct'
); );
function stageChildren($showAll = false) { public function stageChildren($showAll = false) {
// @todo Implement $showAll // @todo Implement $showAll
return $this->MyProducts(); return $this->MyProducts();
} }
function liveChildren($showAll = false) { public function liveChildren($showAll = false) {
// @todo Implement $showAll // @todo Implement $showAll
return $this->MyProducts(); return $this->MyProducts();
} }
function numChildren() { public function numChildren() {
return $this->MyProducts()->Count(); return $this->MyProducts()->Count();
} }
} } } }
@ -210,7 +210,7 @@ The `[api:LeftAndMain]` tree supports multiple parents. We overload CMSTreeClas
the class list. the class list.
:::php :::php
function CMSTreeClasses($controller) { public function CMSTreeClasses($controller) {
return parent::CMSTreeClasses($controller) . ' manyparents'; return parent::CMSTreeClasses($controller) . ' manyparents';
} }
@ -219,10 +219,10 @@ Don't forget to define a new Parent() method that also references your new many-
up the hierarchy! up the hierarchy!
:::php :::php
function getParent() { public function getParent() {
return $this->Parent(); return $this->Parent();
} }
function Parent() { public function Parent() {
$parents = $this->Parents(); $parents = $this->Parents();
if($parents) return $parents->First(); if($parents) return $parents->First();
} }
@ -245,7 +245,7 @@ saved into the database. This will represent our dynamic groups.
### LeftAndMain::getSiteTreeFor() ### LeftAndMain::getSiteTreeFor()
Currently LeftAndMain::getSiteTreeFor() Calls LeftAndMain::getRecord($id) to get a new record. We need to instead Currently LeftAndMain::getSiteTreeFor() Calls LeftAndMain::getRecord($id) to get a new record. We need to instead
create a new function getTreeRecord($id) which will be able to create BlogMonthTreeNode objects as well as look up create a new public function getTreeRecord($id) which will be able to create BlogMonthTreeNode objects as well as look up
SiteTree records from the database. SiteTree records from the database.
The IDs don't **need** be numeric; so we can set the system to allow for 2 $id formats. The IDs don't **need** be numeric; so we can set the system to allow for 2 $id formats.

View File

@ -79,7 +79,7 @@ Raw SQL is handy for performance-optimized calls.
:::php :::php
class Team extends DataObject { class Team extends DataObject {
function getPlayerCount() { public function getPlayerCount() {
$sqlQuery = new SQLQuery( $sqlQuery = new SQLQuery(
"COUNT(Player.ID)", "COUNT(Player.ID)",
"Team LEFT JOIN Player ON Team.ID = Player.TeamID" "Team LEFT JOIN Player ON Team.ID = Player.TeamID"

View File

@ -31,7 +31,7 @@ publisher to generate folders and HTML-files.
* Return a list of all the pages to cache * Return a list of all the pages to cache
*/ */
function allPagesToCache() { public function allPagesToCache() {
// Get each page type to define its sub-urls // Get each page type to define its sub-urls
$urls = array(); $urls = array();
@ -52,7 +52,7 @@ publisher to generate folders and HTML-files.
* Get a list of URLs to cache related to this page * Get a list of URLs to cache related to this page
*/ */
function subPagesToCache() { public function subPagesToCache() {
$urls = array(); $urls = array();
// add current page // add current page
@ -66,7 +66,7 @@ publisher to generate folders and HTML-files.
return $urls; return $urls;
} }
function pagesAffectedByChanges() { public function pagesAffectedByChanges() {
$urls = $this->subPagesToCache(); $urls = $this->subPagesToCache();
if($p = $this->Parent) $urls = array_merge((array)$urls, (array)$p->subPagesToCache()); if($p = $this->Parent) $urls = array_merge((array)$urls, (array)$p->subPagesToCache());
return $urls; return $urls;
@ -80,7 +80,7 @@ cache then you unset these URLs from the returned array. If you do not want to c
you can also add an exclusion you can also add an exclusion
:::php :::php
function allPagesToCache() { public function allPagesToCache() {
$urls = array(); $urls = array();
$pages = DataObject::get("SiteTree"); $pages = DataObject::get("SiteTree");
@ -100,7 +100,7 @@ you can also add an exclusion
You can also pass the filtering to the original DataObject::get("SiteTree"); You can also pass the filtering to the original DataObject::get("SiteTree");
:::php :::php
function allPagesToCache() { public function allPagesToCache() {
$urls = array(); $urls = array();
$pages = DataObject::get("SiteTree", "ClassName != 'UserDefinedForm'"); $pages = DataObject::get("SiteTree", "ClassName != 'UserDefinedForm'");
... ...
@ -150,7 +150,7 @@ Instead of the above code snippet for Page.php, use the following code:
// ... // ...
function allPagesToCache() { public function allPagesToCache() {
// Get each page type to define its sub-urls // Get each page type to define its sub-urls
$urls = array(); $urls = array();
@ -164,13 +164,13 @@ Instead of the above code snippet for Page.php, use the following code:
return $urls; return $urls;
} }
function subPagesToCache() { public function subPagesToCache() {
$urls = array(); $urls = array();
$urls[] = $this->AbsoluteLink(); $urls[] = $this->AbsoluteLink();
return $urls; return $urls;
} }
function pagesAffectedByChanges() { public function pagesAffectedByChanges() {
$urls = $this->subPagesToCache(); $urls = $this->subPagesToCache();
if($p = $this->Parent) $urls = array_merge((array)$urls, (array)$p->subPagesToCache()); if($p = $this->Parent) $urls = array_merge((array)$urls, (array)$p->subPagesToCache());
return $urls; return $urls;

View File

@ -13,7 +13,7 @@ directly as a button on each record, as well as filtering, and sorting. It also
allowing export of data as a CSV. allowing export of data as a CSV.
:::php :::php
function getReportField() { public function getReportField() {
$resultSet = new DataObjectSet(); $resultSet = new DataObjectSet();
$filter = `; $filter = `;
$sort = "Member.ID ASC"; $sort = "Member.ID ASC";
@ -104,7 +104,7 @@ For more information on each of the features used in the example, you can read b
// Product.php Example // Product.php Example
class Product extends DataObject { class Product extends DataObject {
$has_one = array('Buyer'=>'Member'); $has_one = array('Buyer'=>'Member');
function getPriceWithShipping() { public function getPriceWithShipping() {
return $this->Price + $this->Shipping; return $this->Price + $this->Shipping;
} }
} }
@ -263,7 +263,7 @@ Please subclass `[api:TableListField]` to implement custom sorting, following th
:::php :::php
class CustomTableListField extends TableListField { class CustomTableListField extends TableListField {
// referenced through "dateAverage" // referenced through "dateAverage"
function colFunction_dateAverage($values) { public function colFunction_dateAverage($values) {
// custom date summaries // custom date summaries
} }
} }

View File

@ -326,7 +326,7 @@ There are two ways you can extend the template variables you have available. You
**mysite/code/Page.php** **mysite/code/Page.php**
... ...
function MyCustomValue() { public function MyCustomValue() {
return "Hi, this is my site"; return "Hi, this is my site";
} }
@ -344,7 +344,7 @@ Your function could return a single value as above or it could be a subclass of
:::php :::php
.. ..
function MyCustomValues() { public function MyCustomValues() {
return new ArrayData(array("Hi" => "Kia Ora", "Name" => "John Smith")); return new ArrayData(array("Hi" => "Kia Ora", "Name" => "John Smith"));
} }
@ -376,7 +376,7 @@ For example, this Controller method
:::php :::php
private $counter = 0; private $counter = 0;
function Counter() { public function Counter() {
$this->counter += 1; $this->counter += 1;
return $this->counter; return $this->counter;
} }
@ -451,11 +451,11 @@ default if it exists and there is no action in the url parameters.
:::php :::php
class MyPage_Controller extends Page_Controller { class MyPage_Controller extends Page_Controller {
function init(){ public function init(){
parent::init(); parent::init();
} }
function index() { public function index() {
if(Director::is_ajax()) { if(Director::is_ajax()) {
return $this->renderWith("myAjaxTemplate"); return $this->renderWith("myAjaxTemplate");
} }

View File

@ -93,7 +93,7 @@ Sometimes, it's not enough to add a class, you also want to remove the typograph
This example sets another CSS class typographybis: This example sets another CSS class typographybis:
:::php :::php
function getCMSFields() { public function getCMSFields() {
... ...
$htmleditor = new HTMLEditorField("ContentBis", "Content Bis"); $htmleditor = new HTMLEditorField("ContentBis", "Content Bis");
$htmleditor->setCSSClass('typographybis'); $htmleditor->setCSSClass('typographybis');

View File

@ -12,7 +12,7 @@ whenever a blog entry has been published.
:::php :::php
class Page extends SiteTree { class Page extends SiteTree {
// ... // ...
function publish($fromStage, $toStage, $createNewVersion = false) { public function publish($fromStage, $toStage, $createNewVersion = false) {
mail("sam@silverstripe.com", "Blog published", "The blog has been published"); mail("sam@silverstripe.com", "Blog published", "The blog has been published");
return $this->extension_instances['Versioned']->publish($fromStage, $toStage, $createNewVersion); return $this->extension_instances['Versioned']->publish($fromStage, $toStage, $createNewVersion);
} }
@ -24,7 +24,7 @@ whenever a blog entry has been published.
:::php :::php
class Page extends SiteTree { class Page extends SiteTree {
// ... // ...
function onAfterPublish() { public function onAfterPublish() {
mail("sam@silverstripe.com", "Blog published", "The blog has been published"); mail("sam@silverstripe.com", "Blog published", "The blog has been published");
parent::onAfterPublish(); parent::onAfterPublish();
} }

View File

@ -98,7 +98,7 @@ This code provides a good template:
:::php :::php
class MyProcess extends Controller { class MyProcess extends Controller {
function index() { public function index() {
set_time_limit(0); set_time_limit(0);
while(memory_get_usage() < 32*1024*1024) { while(memory_get_usage() < 32*1024*1024) {
if($this->somethingToDo()) { if($this->somethingToDo()) {

View File

@ -12,7 +12,7 @@ your SilverStripe site.
<?php <?php
class FastFood_Controller extends Controller { class FastFood_Controller extends Controller {
function order($arguments) { public function order($arguments) {
print_r($arguments); print_r($arguments);
} }
} }

View File

@ -17,7 +17,7 @@ In your controller (e.g. `mysite/code/Page.php`):
:::php :::php
class Page_Controller { class Page_Controller {
function init() { public function init() {
// either specify the css file manually // either specify the css file manually
Requirements::css("mymodule/css/my.css", "screen,projection"); Requirements::css("mymodule/css/my.css", "screen,projection");
// or mention the css filename and SilverStripe will get the file from the current theme and add it to the template // or mention the css filename and SilverStripe will get the file from the current theme and add it to the template

View File

@ -340,7 +340,7 @@ default behaviour by making a function called "get`<fieldname>`" or "set`<fieldn
); );
// access through $myPlayer->Status // access through $myPlayer->Status
function getStatus() { public function getStatus() {
// check if the Player is actually... born already! // check if the Player is actually... born already!
return (!$this->obj("Birthday")->InPast()) ? "Unborn" : $this->Status; return (!$this->obj("Birthday")->InPast()) ? "Unborn" : $this->Status;
} }
@ -353,13 +353,13 @@ Here we combined a Player's first name and surname, accessible through $myPlayer
:::php :::php
class Player extends DataObject { class Player extends DataObject {
function getTitle() { public function getTitle() {
return "{$this->FirstName} {$this->Surname}"; return "{$this->FirstName} {$this->Surname}";
} }
// access through $myPlayer->Title = "John Doe"; // access through $myPlayer->Title = "John Doe";
// just saves data on the object, please use $myPlayer->write() to save the database-row // just saves data on the object, please use $myPlayer->write() to save the database-row
function setTitle($title) { public function setTitle($title) {
list($firstName, $surName) = explode(' ', $title); list($firstName, $surName) = explode(' ', $title);
$this->FirstName = $firstName; $this->FirstName = $firstName;
$this->Surname = $surName; $this->Surname = $surName;
@ -409,7 +409,7 @@ but using the *obj()*-method or accessing through a template will cast the value
// $myPlayer->MembershipFee() returns a float (e.g. 123.45) // $myPlayer->MembershipFee() returns a float (e.g. 123.45)
// $myPlayer->obj('MembershipFee') returns a object of type Currency // $myPlayer->obj('MembershipFee') returns a object of type Currency
// In a template: <% control MyPlayer %>MembershipFee.Nice<% end_control %> returns a casted string (e.g. "$123.45") // In a template: <% control MyPlayer %>MembershipFee.Nice<% end_control %> returns a casted string (e.g. "$123.45")
function getMembershipFee() { public function getMembershipFee() {
return $this->Team()->BaseFee * $this->MembershipYears; return $this->Team()->BaseFee * $this->MembershipYears;
} }
} }
@ -542,7 +542,7 @@ Inside sapphire it doesn't matter if you're editing a *has_many*- or a *many_man
* @param DataObjectSet * @param DataObjectSet
*/ */
function addCategories($additionalCategories) { public function addCategories($additionalCategories) {
$existingCategories = $this->Categories(); $existingCategories = $this->Categories();
// method 1: Add many by iteration // method 1: Add many by iteration
@ -569,7 +569,7 @@ the described relations).
); );
// can be accessed by $myTeam->ActivePlayers() // can be accessed by $myTeam->ActivePlayers()
function ActivePlayers() { public function ActivePlayers() {
return $this->Players("Status='Active'"); return $this->Players("Status='Active'");
} }
} }
@ -655,7 +655,7 @@ Example: Disallow creation of new players if the currently logged-in player is n
"Teams"=>"Team" "Teams"=>"Team"
); );
function onBeforeWrite() { public function onBeforeWrite() {
// check on first write action, aka "database row creation" (ID-property is not set) // check on first write action, aka "database row creation" (ID-property is not set)
if(!$this->ID) { if(!$this->ID) {
$currentPlayer = Member::currentUser(); $currentPlayer = Member::currentUser();
@ -695,7 +695,7 @@ It checks if a member is logged in who belongs to a group containing the permiss
"Teams"=>"Team" "Teams"=>"Team"
); );
function onBeforeDelete() { public function onBeforeDelete() {
if(!Permission::check('PLAYER_DELETE')) { if(!Permission::check('PLAYER_DELETE')) {
Security::permissionFailure($this); Security::permissionFailure($this);
exit(); exit();

View File

@ -12,7 +12,7 @@ class.
:::php :::php
function Form() { public function Form() {
$form = new Form($this, 'Form', $form = new Form($this, 'Form',
new FieldList( new FieldList(
new TextField('MyRequiredField'), new TextField('MyRequiredField'),

View File

@ -21,7 +21,7 @@ have problems with form action handler not working, check that these values are
Example: Example:
:::php :::php
function MyCustomForm() { public function MyCustomForm() {
$fields = new FieldList( $fields = new FieldList(
new EmailField("Email"), new EmailField("Email"),
new EncryptField("Password") new EncryptField("Password")
@ -43,7 +43,7 @@ $name must be passed - their values depend on where the form is instantiated.
:::php :::php
class MyForm extends Form { class MyForm extends Form {
function __construct($controller, $name) { public function __construct($controller, $name) {
$fields = new FieldList( $fields = new FieldList(
new EmailField("Email"), new EmailField("Email"),
new EncryptedField("Password") new EncryptedField("Password")
@ -167,7 +167,7 @@ First of all, you need to create your form on it's own class, that way you can d
:::php :::php
class MyForm extends Form { class MyForm extends Form {
function __construct($controller, $name) { public function __construct($controller, $name) {
$fields = new FieldList( $fields = new FieldList(
new TextField('FirstName', 'First name'), new TextField('FirstName', 'First name'),
new EmailField('Email', 'Email address') new EmailField('Email', 'Email address')
@ -180,14 +180,14 @@ First of all, you need to create your form on it's own class, that way you can d
parent::__construct($controller, $name, $fields, $actions); parent::__construct($controller, $name, $fields, $actions);
} }
function forTemplate() { public function forTemplate() {
return $this->renderWith(array( return $this->renderWith(array(
$this->class, $this->class,
'Form' 'Form'
)); ));
} }
function submit($data, $form) { public function submit($data, $form) {
// do stuff here // do stuff here
} }
@ -269,7 +269,7 @@ If you want to remove certain fields from your subclass:
:::php :::php
class MyCustomForm extends MyForm { class MyCustomForm extends MyForm {
function __construct($controller, $name) { public function __construct($controller, $name) {
parent::__construct($controller, $name); parent::__construct($controller, $name);
// remove a normal field // remove a normal field

View File

@ -12,7 +12,7 @@ This example might come from a Controller designed to manage the members of a gr
/** /**
* Form to display all members in a group * Form to display all members in a group
*/ */
function MemberForm() { public function MemberForm() {
$field = new GridField("Members", "Members of this group", $this->group->Members()); $field = new GridField("Members", "Members of this group", $this->group->Members());
return new Form("MemberForm", $this, new FieldSet($field), new FieldSet()); return new Form("MemberForm", $this, new FieldSet($field), new FieldSet());
} }
@ -134,7 +134,7 @@ For example, this components will add a footer row to the grid field, thanking t
:::php :::php
class ThankYouForUsingSilverStripe implements GridField_HTMLProvider { class ThankYouForUsingSilverStripe implements GridField_HTMLProvider {
function getHTMLFragments($gridField) { public function getHTMLFragments($gridField) {
$colSpan = $gridField->getColumnCount(); $colSpan = $gridField->getColumnCount();
return array( return array(
'footer' => '<tr><td colspan="' . $colSpan . '">Thank you for using SilverStripe!</td></tr>', 'footer' => '<tr><td colspan="' . $colSpan . '">Thank you for using SilverStripe!</td></tr>',
@ -211,13 +211,13 @@ Here is an example in full. The actual implementation of the view and edit form
* - <FormURL>/field/<GridFieldName>/item/<RecordID>/edit * - <FormURL>/field/<GridFieldName>/item/<RecordID>/edit
*/ */
class GridFieldPopupForms implements GridField_URLHandler { class GridFieldPopupForms implements GridField_URLHandler {
function getURLHandlers($gridField) { public function getURLHandlers($gridField) {
return array( return array(
'item/$ID' => 'handleItem', 'item/$ID' => 'handleItem',
); );
} }
function handleItem($gridField, $request) { public function handleItem($gridField, $request) {
$record = $gridField->getList()->byId($request->param("ID")); $record = $gridField->getList()->byId($request->param("ID"));
return new GridFieldPopupForm_ItemRequest($gridField, $this, $record); return new GridFieldPopupForm_ItemRequest($gridField, $this, $record);
} }
@ -228,18 +228,18 @@ Here is an example in full. The actual implementation of the view and edit form
protected $component; protected $component;
protected $record; protected $record;
function __construct($gridField, $component, $record) { public function __construct($gridField, $component, $record) {
$this->gridField = $gridField; $this->gridField = $gridField;
$this->component = $gridField; $this->component = $gridField;
$this->record = $record; $this->record = $record;
parent::__construct(); parent::__construct();
} }
function index() { public function index() {
echo "view form for record #" . $record->ID; echo "view form for record #" . $record->ID;
} }
function edit() { public function edit() {
echo "edit form for record #" . $record->ID; echo "edit form for record #" . $record->ID;
} }
} }

View File

@ -138,7 +138,7 @@ below), which is the starting point for translations.
Here is the function prototype of this translator function Here is the function prototype of this translator function
:::php :::php
function _t(string $entity [, string $string [, int $priority [, string $context]]]) { public function _t(string $entity [, string $string [, int $priority [, string $context]]]) {
**$entity:** The first parameter is the identifier, and is composed by a namespace and an entity name, with a dot separating them. **$entity:** The first parameter is the identifier, and is composed by a namespace and an entity name, with a dot separating them.

View File

@ -24,7 +24,7 @@ init() function on your module controller classes:
:::php :::php
class Forum_Controller extends Page_Controller { class Forum_Controller extends Page_Controller {
function init() { public function init() {
if(Director::fileExists(project() . "/css/forum.css")) { if(Director::fileExists(project() . "/css/forum.css")) {
Requirements::css(project() . "/css/forum.css"); Requirements::css(project() . "/css/forum.css");
}else{ }else{

View File

@ -91,7 +91,7 @@ want the MenuTitle field to show on your page, which is inherited from `[api:Sit
:::php :::php
class StaffPage extends Page { class StaffPage extends Page {
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeFieldFromTab('Root.Content', 'MenuTitle'); $fields->removeFieldFromTab('Root.Content', 'MenuTitle');
return $fields; return $fields;
@ -111,7 +111,7 @@ required on a certain page-type.
:::php :::php
class MyForm extends Form { class MyForm extends Form {
function __construct($controller, $name) { public function __construct($controller, $name) {
// add a default FieldList of form fields // add a default FieldList of form fields
$member = singleton('Member'); $member = singleton('Member');

View File

@ -52,7 +52,7 @@ Example:
:::php :::php
class MyForm extends Form { class MyForm extends Form {
function save($RAW_data, $form) { public function save($RAW_data, $form) {
$SQL_data = Convert::raw2sql($RAW_data); // works recursively on an array $SQL_data = Convert::raw2sql($RAW_data); // works recursively on an array
$objs = DataObject::get('Player', "Name = '{$SQL_data[name]}'"); $objs = DataObject::get('Player', "Name = '{$SQL_data[name]}'");
// ... // ...
@ -67,7 +67,7 @@ Example:
:::php :::php
class MyController extends Controller { class MyController extends Controller {
function myurlaction($RAW_urlParams) { public function myurlaction($RAW_urlParams) {
$SQL_urlParams = Convert::raw2sql($RAW_urlParams); // works recursively on an array $SQL_urlParams = Convert::raw2sql($RAW_urlParams); // works recursively on an array
$objs = DataObject::get('Player', "Name = '{$SQL_data[OtherID]}'"); $objs = DataObject::get('Player', "Name = '{$SQL_data[OtherID]}'");
// ... // ...
@ -84,12 +84,12 @@ This means if you've got a chain of functions passing data through, escaping sho
* @param array $RAW_data All names in an indexed array (not SQL-safe) * @param array $RAW_data All names in an indexed array (not SQL-safe)
*/ */
function saveAllNames($RAW_data) { public function saveAllNames($RAW_data) {
// $SQL_data = Convert::raw2sql($RAW_data); // premature escaping // $SQL_data = Convert::raw2sql($RAW_data); // premature escaping
foreach($RAW_data as $item) $this->saveName($item); foreach($RAW_data as $item) $this->saveName($item);
} }
function saveName($RAW_name) { public function saveName($RAW_name) {
$SQL_name = Convert::raw2sql($RAW_name); $SQL_name = Convert::raw2sql($RAW_name);
DB::query("UPDATE Player SET Name = '{$SQL_name}'"); DB::query("UPDATE Player SET Name = '{$SQL_name}'");
} }
@ -178,7 +178,7 @@ PHP:
'TitleWithHTMLSuffix' => 'HTMLText' // optional, as HTMLText is the default casting 'TitleWithHTMLSuffix' => 'HTMLText' // optional, as HTMLText is the default casting
); );
function TitleWithHTMLSuffix($suffix) { public function TitleWithHTMLSuffix($suffix) {
// $this->Title is not casted in PHP // $this->Title is not casted in PHP
return $this->Title . '<small>(' . $suffix. ')</small>'; return $this->Title . '<small>(' . $suffix. ')</small>';
} }
@ -210,7 +210,7 @@ PHP:
:::php :::php
class MyController extends Controller { class MyController extends Controller {
function search($request) { public function search($request) {
$htmlTitle = '<p>Your results for:' . Convert::raw2xml($request->getVar('Query')) . '</p>'; $htmlTitle = '<p>Your results for:' . Convert::raw2xml($request->getVar('Query')) . '</p>';
return $this->customise(array( return $this->customise(array(
'Query' => DBField::create('Text', $request->getVar('Query')), 'Query' => DBField::create('Text', $request->getVar('Query')),
@ -239,7 +239,7 @@ PHP:
:::php :::php
class MyController extends Controller { class MyController extends Controller {
function search($request) { public function search($request) {
$rssRelativeLink = "/rss?Query=" . urlencode($_REQUEST['query']) . "&sortOrder=asc"; $rssRelativeLink = "/rss?Query=" . urlencode($_REQUEST['query']) . "&sortOrder=asc";
$rssLink = Controller::join_links($this->Link(), $rssRelativeLink); $rssLink = Controller::join_links($this->Link(), $rssRelativeLink);
return $this->customise(array( return $this->customise(array(
@ -294,7 +294,7 @@ passed, such as *mysite.com/home/add/dfsdfdsfd*, then it returns 0.
Below is an example with different ways you would use this casting technique: Below is an example with different ways you would use this casting technique:
:::php :::php
function CaseStudies() { public function CaseStudies() {
// cast an ID from URL parameters e.g. (mysite.com/home/action/ID) // cast an ID from URL parameters e.g. (mysite.com/home/action/ID)
$anotherID = (int)Director::urlParam['ID']; $anotherID = (int)Director::urlParam['ID'];

View File

@ -17,7 +17,7 @@ URLs. Here is an example from the subsites module:
/** /**
* Return a session that has a user logged in as an administrator * Return a session that has a user logged in as an administrator
*/ */
function adminLoggedInSession() { public function adminLoggedInSession() {
return new Session(array( return new Session(array(
'loggedInAs' => $this->idFromFixture('Member', 'admin') 'loggedInAs' => $this->idFromFixture('Member', 'admin')
)); ));
@ -26,7 +26,7 @@ URLs. Here is an example from the subsites module:
/** /**
* Test generation of the view * Test generation of the view
*/ */
function testBasicView() { public function testBasicView() {
// Open the admin area logged in as admin // Open the admin area logged in as admin
$response1 = Director::test('admin/subsites/', null, $this->adminLoggedInSession()); $response1 = Director::test('admin/subsites/', null, $this->adminLoggedInSession());

View File

@ -24,7 +24,7 @@ provides us the basics of creating unit tests.
* - Generates from Title by default, unless URLSegment is explicitly set * - Generates from Title by default, unless URLSegment is explicitly set
* - Resolves duplicates by appending a number * - Resolves duplicates by appending a number
*/ */
function testURLGeneration() { public function testURLGeneration() {
$expectedURLs = array( $expectedURLs = array(
'home' => 'home', 'home' => 'home',
'staff' => 'my-staff', 'staff' => 'my-staff',

View File

@ -51,7 +51,7 @@ Widget Form to manage the widgets. An example of this is below
"Sidebar" => "WidgetArea", "Sidebar" => "WidgetArea",
); );
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Content.Widgets", new WidgetAreaEditor("Sidebar")); $fields->addFieldToTab("Root.Content.Widgets", new WidgetAreaEditor("Sidebar"));
return $fields; return $fields;
@ -113,7 +113,7 @@ An example widget is below:
static $cmsTitle = "Flickr Photos"; static $cmsTitle = "Flickr Photos";
static $description = "Shows flickr photos."; static $description = "Shows flickr photos.";
function Photos() { public function Photos() {
Requirements::javascript("sapphire/thirdparty/prototype/prototype.js"); Requirements::javascript("sapphire/thirdparty/prototype/prototype.js");
Requirements::javascript("sapphire/thirdparty/scriptaculous/effects.js"); Requirements::javascript("sapphire/thirdparty/scriptaculous/effects.js");
Requirements::javascript("mashups/javascript/lightbox.js"); Requirements::javascript("mashups/javascript/lightbox.js");
@ -138,7 +138,7 @@ An example widget is below:
return $output; return $output;
} }
function getCMSFields() { public function getCMSFields() {
return new FieldList( return new FieldList(
new TextField("User", "User"), new TextField("User", "User"),
new TextField("PhotoSet", "Photo Set"), new TextField("PhotoSet", "Photo Set"),
@ -170,7 +170,7 @@ This example creates an RSSWidget with the SilverStripe blog feed.
:::php :::php
<?php <?php
function SilverStripeFeed() { public function SilverStripeFeed() {
$widget = new RSSWidget(); $widget = new RSSWidget();
$widget->RssUrl = "http://feeds.feedburner.com/silverstripe-blog"; $widget->RssUrl = "http://feeds.feedburner.com/silverstripe-blog";
return $widget->renderWith("WidgetHolder"); return $widget->renderWith("WidgetHolder");
@ -205,7 +205,7 @@ variable. For example, to set your widgets title to 'Hello World!', you could us
**widgets_yourWidget/YourWidgetWidget.php** **widgets_yourWidget/YourWidgetWidget.php**
:::php :::php
function Title() { public function Title() {
return "Hello World!"; return "Hello World!";
} }
@ -217,7 +217,7 @@ widget called WidgetTitle, that you wish to use as your title. If nothing is set
This is similar to the RSS Widget in the blog module. This is similar to the RSS Widget in the blog module.
:::php :::php
function Title() { public function Title() {
return $this->WidgetTitle ? $this->WidgetTitle : self::$title; return $this->WidgetTitle ? $this->WidgetTitle : self::$title;
} }
@ -242,7 +242,7 @@ sure that your controller follows the usual naming conventions, and it will be a
} }
class MyWidget_Controller extends Widget_Controller { class MyWidget_Controller extends Widget_Controller {
function MyFormName() { public function MyFormName() {
return new Form( return new Form(
$this, $this,
'MyFormName', 'MyFormName',
@ -255,7 +255,7 @@ sure that your controller follows the usual naming conventions, and it will be a
); );
} }
function doAction($data, $form) { public function doAction($data, $form) {
// $this->widget points to the widget // $this->widget points to the widget
} }
} }
@ -295,7 +295,7 @@ Page class). One way to fix this is to comment out line 30 in BlogHolder.php and
// "SideBar" => "WidgetArea", COMMENT OUT // "SideBar" => "WidgetArea", COMMENT OUT
'Newsletter' => 'NewsletterType' 'Newsletter' => 'NewsletterType'
....... .......
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->removeFieldFromTab("Root.Content","Content"); $fields->removeFieldFromTab("Root.Content","Content");
// $fields->addFieldToTab("Root.Content.Widgets", new WidgetAreaEditor("SideBar")); COMMENT OUT // $fields->addFieldToTab("Root.Content.Widgets", new WidgetAreaEditor("SideBar")); COMMENT OUT

View File

@ -171,7 +171,7 @@ method to the *ArticlePage* class.
class ArticlePage extends Page { class ArticlePage extends Page {
// ... // ...
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Content', new DateField('Date'), 'Content'); $fields->addFieldToTab('Root.Content', new DateField('Date'), 'Content');
@ -229,7 +229,7 @@ To make the date field a bit more user friendly, you can add a dropdown calendar
// ..... // .....
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Content', $dateField = new DateField('Date','Article Date (for example: 20/12/2010)'), 'Content'); $fields->addFieldToTab('Root.Content', $dateField = new DateField('Date','Article Date (for example: 20/12/2010)'), 'Content');
@ -472,7 +472,7 @@ control. We can get the data for the news articles by implementing our own funct
:::php :::php
... ...
function LatestNews($num=5) { public function LatestNews($num=5) {
$news = DataObject::get_one("ArticleHolder"); $news = DataObject::get_one("ArticleHolder");
return ($news) ? DataObject::get("ArticlePage", "ParentID = $news->ID", "Date DESC", "", $num) : false; return ($news) ? DataObject::get("ArticlePage", "ParentID = $news->ID", "Date DESC", "", $num) : false;
} }
@ -518,7 +518,7 @@ providing an `[api:RSSFeed]` class to do all the hard work for you. Create the f
*ArticleHolder_Controller*: *ArticleHolder_Controller*:
:::php :::php
function rss() { public function rss() {
$rss = new RSSFeed($this->Children(), $this->Link(), "The coolest news around"); $rss = new RSSFeed($this->Children(), $this->Link(), "The coolest news around");
$rss->outputToBrowser(); $rss->outputToBrowser();
} }
@ -538,7 +538,7 @@ Now all we need is to let the user know that our RSS feed exists. The `[api:RSSF
called when the page is requested. Add this function to *ArticleHolder_Controller*: called when the page is requested. Add this function to *ArticleHolder_Controller*:
:::php :::php
function init() { public function init() {
RSSFeed::linkToFeed($this->Link() . "rss"); RSSFeed::linkToFeed($this->Link() . "rss");
parent::init(); parent::init();
} }
@ -591,7 +591,7 @@ insert an image in the *$Content* field).
'Photo' => 'Image' 'Photo' => 'Image'
); );
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Content.Images", new ImageField('Photo')); $fields->addFieldToTab("Root.Content.Images", new ImageField('Photo'));

View File

@ -31,7 +31,7 @@ the form in a method on *HomePage_Controller*.
class HomePage_Controller extends Page_Controller { class HomePage_Controller extends Page_Controller {
// ... // ...
function BrowserPollForm() { public function BrowserPollForm() {
// Create fields // Create fields
$fields = new FieldList( $fields = new FieldList(
new TextField('Name'), new TextField('Name'),
@ -203,7 +203,7 @@ that the *BrowserPollSubmission* table is created. Now we just need to define 'd
:::php :::php
class HomePage_Controller extends Page_Controller { class HomePage_Controller extends Page_Controller {
// ... // ...
function doBrowserPoll($data, $form) { public function doBrowserPoll($data, $form) {
$submission = new BrowserPollSubmission(); $submission = new BrowserPollSubmission();
$form->saveInto($submission); $form->saveInto($submission);
$submission->write(); $submission->write();
@ -236,7 +236,7 @@ Change the end of the 'BrowserPollForm' function so it looks like this:
** mysite/code/HomePage.php ** ** mysite/code/HomePage.php **
:::php :::php
function BrowserPollForm() { public function BrowserPollForm() {
... ...
// Create validator // Create validator
@ -271,7 +271,7 @@ First modify the 'doBrowserPoll' to set the session variable 'BrowserPollVoted'
HomePage_Controller extends Page_Controller { HomePage_Controller extends Page_Controller {
... ...
function doBrowserPoll($data, $form) { public function doBrowserPoll($data, $form) {
$submission = new BrowserPollSubmission(); $submission = new BrowserPollSubmission();
$form->saveInto($submission); $form->saveInto($submission);
$submission->write(); $submission->write();
@ -289,7 +289,7 @@ Then we simply need to check if the session variable has been set in 'BrowserPol
it is. it is.
:::php :::php
function BrowserPollForm() { public function BrowserPollForm() {
if(Session::get('BrowserPollVoted')) { if(Session::get('BrowserPollVoted')) {
return false; return false;
} }
@ -320,7 +320,7 @@ then create our graph using a page control in the template. Create the function
** mysite/code/HomePage.php ** ** mysite/code/HomePage.php **
:::php :::php
function BrowserPollResults() { public function BrowserPollResults() {
$submissions = DataObject::get('BrowserPollSubmission'); $submissions = DataObject::get('BrowserPollSubmission');
$total = $submissions->Count(); $total = $submissions->Count();

View File

@ -117,7 +117,7 @@ Next we need to create the *results* function.
class Page_Controller extends ContentController { class Page_Controller extends ContentController {
... ...
function results($data, $form){ public function results($data, $form){
$data = array( $data = array(
'Results' => $form->getResults(), 'Results' => $form->getResults(),
'Query' => $form->getSearchQuery(), 'Query' => $form->getSearchQuery(),

View File

@ -82,7 +82,7 @@ The first step is to create the student and project objects.
'Nationality' => 'Text' 'Nationality' => 'Text'
); );
function getCMSFields_forPopup() { public function getCMSFields_forPopup() {
$fields = new FieldList(); $fields = new FieldList();
$fields->push( new TextField( 'FirstName', 'First Name' ) ); $fields->push( new TextField( 'FirstName', 'First Name' ) );
@ -119,7 +119,7 @@ The second step is to add the table in the method *getCMSFields* which will allo
... ...
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$tablefield = new HasOneComplexTableField( $tablefield = new HasOneComplexTableField(
@ -206,7 +206,7 @@ To use your *HasOneComplexTableField* table for a **1-to-1** relation, make this
... ...
function getCMSFields() { public function getCMSFields() {
... ...
@ -256,7 +256,7 @@ The first step is to create the mentor object and set the relation with the *Stu
'Students' => 'Student' 'Students' => 'Student'
); );
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
$fields->addFieldToTab( 'Root.Content', new TextField( 'FirstName' ) ); $fields->addFieldToTab( 'Root.Content', new TextField( 'FirstName' ) );
@ -295,7 +295,7 @@ The second step is to add the table in the method *getCMSFields* which will allo
... ...
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
... ...
@ -380,7 +380,7 @@ The first step is to create the module object and set the relation with the *Pro
'Projects' => 'Project' 'Projects' => 'Project'
); );
function getCMSFields_forPopup() { public function getCMSFields_forPopup() {
$fields = new FieldList(); $fields = new FieldList();
$fields->push( new TextField( 'Name' ) ); $fields->push( new TextField( 'Name' ) );
return $fields; return $fields;
@ -413,7 +413,7 @@ relation.
... ...
function getCMSFields() { public function getCMSFields() {
$fields = parent::getCMSFields(); $fields = parent::getCMSFields();
... ...
@ -638,7 +638,7 @@ from templates either within a control block or dot notation.
*tutorial/code/Student.php, tutorial/code/Mentor.php* *tutorial/code/Student.php, tutorial/code/Mentor.php*
:::php :::php
function PersonalInfo() { public function PersonalInfo() {
$template = 'GSOCPerson'; $template = 'GSOCPerson';
return $this->renderWith( $template ); return $this->renderWith( $template );
} }
@ -702,7 +702,7 @@ it *MyProject* for instance.
... ...
function MyProject() { public function MyProject() {
return DataObject::get( 'Project', "`MyStudentID` = '{$this->ID}'" ); return DataObject::get( 'Project', "`MyStudentID` = '{$this->ID}'" );
} }