### Setup and Teardown for Test Cases Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/06_Testing/00_Unit_Testing.md Use `setUp()` and `tearDown()` methods to perform actions before and after each test method. This example demonstrates creating multiple pages and modifying configuration settings. ```php namespace App\Test; use SilverStripe\Core\Config\Config; use SilverStripe\Dev\SapphireTest; use SilverStripe\Versioned\Versioned; class PageTest extends SapphireTest { protected $usesDatabase = true; protected function setUp(): void { parent::setUp(); // create 100 pages for ($i = 0; $i < 100; $i++) { $page = new Page(['Title' => "Page $i"]); $page->write(); $page->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE); } // set custom configuration for the test. Config::modify()->update('Foo', 'bar', 'Hello!'); } public function testMyMethod() { // ... } public function testMySecondMethod() { // ... } } ``` -------------------------------- ### Common Sake Commands Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/17_CLI/01_Sake.md Examples of frequently used Sake commands, including listing commands, building the database, flushing the cache, and getting help. ```bash # list available commands sake # or `sake list` ``` ```bash # list available tasks sake tasks ``` ```bash # build the database sake db:build ``` ```bash # flush the cache sake flush # or use the `--flush` flag with any other command ``` ```bash # get help info about a command (including tasks) sake --help # e.g. `sake db:build --help` ``` -------------------------------- ### Install Dependencies and Lint Documentation Source: https://github.com/silverstripe/developer-docs/blob/6/en/10_Contributing/02_Documentation.md Run these commands locally to install project dependencies and lint the documentation before submitting a pull request. Ensure Composer and Yarn are installed. ```bash yarn install composer install yarn lint ``` -------------------------------- ### Install and Use Node.js with NVM Source: https://github.com/silverstripe/developer-docs/blob/6/en/10_Contributing/06_Build_Tooling.md Installs and sets the recommended Node.js version using Node Version Manager (nvm). Ensure nvm is installed and configured before running. ```bash nvm install && nvm use ``` -------------------------------- ### Install Silverstripe and Configure Environment Source: https://context7.com/silverstripe/developer-docs/llms.txt Install Silverstripe using Composer, configure database connection and admin credentials in the .env file, and build the database schema. ```bash composer create-project silverstripe/installer my-project # .env file (place in project root, NOT public/) SS_DATABASE_CLASS="MySQLDatabase" SS_DATABASE_NAME="mysite" SS_DATABASE_SERVER="localhost" SS_DATABASE_USERNAME="dbuser" SS_DATABASE_PASSWORD="secret" SS_DEFAULT_ADMIN_USERNAME="admin" SS_DEFAULT_ADMIN_PASSWORD="password" SS_ENVIRONMENT_TYPE="dev" # dev | test | live vendor/bin/sake db:build ``` -------------------------------- ### Get Service Instance from Injector Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Example of retrieving a service instance using the Injector::inst()->get() method. ```php use App\Control\MyController; use SilverStripe\Core\Injector\Injector; $controller = Injector::inst()->get(MyController::class); ``` -------------------------------- ### Check Composer Installation Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/02_Composer.md Verify that Composer is installed and accessible on your system by running the help command. ```bash composer help ``` -------------------------------- ### Example: Injecting Gallery and SearchBar components Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/12_ReactJS_and_Redux.md This example demonstrates injecting 'GalleryItem' and 'SearchBar' dependencies into a 'Gallery' component, mapping them to 'ItemComponent' and 'SearchComponent' props respectively, and providing a specific context 'Gallery.Search'. ```javascript // my-module/js/components/Gallery.js import React from 'react'; import { inject } from 'lib/Injector'; class Gallery extends React.Component { render() { const { SearchComponent, ItemComponent } = this.props; return (
{this.props.items.map(item => ( ))}
); } } export default inject( ['GalleryItem', 'SearchBar'], (GalleryItem, SearchBar) => ({ ItemComponent: GalleryItem, SearchComponent: SearchBar }), () => 'Gallery.Search' )(Gallery); ``` -------------------------------- ### Install JavaScript Dependencies Source: https://github.com/silverstripe/developer-docs/blob/6/en/10_Contributing/06_Build_Tooling.md Installs all JavaScript dependencies defined in package.json for a module. Run this in the module directory after installing Node.js and Yarn. ```bash yarn install ``` -------------------------------- ### Install Module Using Composer Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/02_Composer.md After defining a custom repository, install the module using the standard composer require command. Composer will use your specified fork. ```bash composer require silverstripe/cms ``` -------------------------------- ### Install Module for Development Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/00_Modules.md Use this command to install a module directly from its source repository, enabling local development. The `--prefer-source` flag ensures Composer pulls directly from Git. ```bash composer require my_vendor/module_name:dev-main --prefer-source ``` -------------------------------- ### Install Silverstripe CMS Project Source: https://github.com/silverstripe/developer-docs/blob/6/en/10_Contributing/01_Code.md Use this command to create a new Silverstripe CMS project installation. Target a specific minor version branch for development. ```bash composer create-project --keep-vcs silverstripe/installer ./your-website-folder 6.1.x-dev ``` -------------------------------- ### Install Dependencies for Pattern Library Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_CMS_Architecture.md Installs project dependencies and Node.js modules required for running the Silverstripe CMS pattern library locally. Ensure you have Composer and Yarn installed. ```bash composer install --prefer-source (cd vendor/silverstripe/asset-admin && yarn install) (cd vendor/silverstripe/cms && yarn install) cd vendor/silverstripe/admin && yarn install && yarn pattern-lib ``` -------------------------------- ### YAML Fixture Example Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/06_Testing/04_Fixtures.md Example of how to define fixture data for Player and Team DataObjects in YAML format. This data will be loaded into the test database. ```yaml Team: Team1: Name: "The Best Team" Origin: "Nowhere" Team2: Name: "The Second Best Team" Origin: "Somewhere" Player: Player1: Name: "John Doe" Team: =>Team.Team1 Player2: Name: "Jane Doe" Team: =>Team.Team1 Player3: Name: "Peter Jones" Team: =>Team.Team2 ``` -------------------------------- ### Install Silverstripe CMS with Composer Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/index.md Use Composer to create a new Silverstripe project. Ensure Composer is installed and accessible in your terminal. ```bash composer create-project silverstripe/installer my-project ``` -------------------------------- ### Implement Factory Interface Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Example of a factory class implementing the SilverStripe\Core\Injector\Factory interface to create service instances. ```php // app/src/MyFactory.php namespace App; use SilverStripe\Core\Injector\Factory; class MyFactory implements Factory { public function create(string $service, array $params = []): object { return new MyServiceImplementation(...$params); } } ``` -------------------------------- ### Example Shortcode Usage Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/04_Shortcodes.md Demonstrates how a shortcode like '[map]' can be embedded in text and parsed into an iframe. ```php $text = '

My Map

[map]' // Will output //

My Map

``` -------------------------------- ### Install Dependencies for Production Deployment Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/02_Composer.md Use this command during deployment to install dependencies based on the `composer.lock` file, excluding development dependencies and optimizing the autoloader for speed. ```bash composer install --no-dev -o ``` -------------------------------- ### Basic Silverstripe CMS Template Example Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/01_Templates/01_Syntax.md This is a standard example of a Silverstripe CMS template file (.ss) demonstrating common syntax elements like variables, conditionals, loops, and includes. ```ss <%-- app/templates/Page.ss --%> <% base_tag %> $Title $MetaTags(false) <% require themedCSS("screen") %>

Bob's Chicken Shack

<% with $CurrentMember %>

Welcome $FirstName $Surname.

<% end_with %> <% if $Dishes %> <% end_if %> <% include Footer %> ``` -------------------------------- ### Configure Custom Application Directory Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/04_Directory_Structure.md Example YAML configuration to change the default application directory from `app/` to `myspecialapp/`. ```yaml # myspecialapp/_config/config.yml --- Name: myspecialapp --- SilverStripe\Core\Manifest\ModuleManifest: project: 'myspecialapp' ``` -------------------------------- ### Example of HTML with a File Shortcode Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/14_Files/01_File_Management.md Illustrates how a file shortcode is embedded within HTML content to display an image. ```html

Welcome to Silverstripe CMS! This is the default homepage.

[image src="/assets/12824172.jpeg" id="27" width="400" height="400" class="leftAlone ss-htmleditorfield-file image" title="My Image"]

``` -------------------------------- ### Example PJAX AJAX HTTP Request Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_CMS_Architecture.md This is an example of an abbreviated AJAX HTTP GET request sent by the client, including the `X-Pjax` header to specify desired fragments. ```text GET /admin/myadmin HTTP/1.1 X-Pjax:MyRecordInfo,Breadcrumbs X-Requested-With:XMLHttpRequest ``` -------------------------------- ### Class-Level Setup and Teardown Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/06_Testing/00_Unit_Testing.md Utilize `setUpBeforeClass()` and `tearDownAfterClass()` for actions that should run only once per test file. Remember to call the parent methods. ```php namespace App\Test; use SilverStripe\Dev\SapphireTest; class PageTest extends SapphireTest { public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); // ... } public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); // ... } // ... } ``` -------------------------------- ### Add Specific Version of Module to Silverstripe Project Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/02_Composer.md Install a specific version of a Silverstripe CMS module by providing a version constraint after the package name. This example installs version 6 or later. ```bash composer require dnadesign/silverstripe-elemental ^6 ``` -------------------------------- ### Get Service Instance Created by Factory Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Example of retrieving a service instance that is created by a factory using the Injector. ```php use App\MyService; use SilverStripe\Core\Injector\Injector; // Uses App\MyFactory::create() to create the service instance, resulting in an instance of App\MyServiceImplementation $instance = Injector::inst()->get(MyService::class); ``` -------------------------------- ### Create Filtered Relation List Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/00_Model/02_Relations.md Define a custom method to retrieve a filtered subset of a relation. This example shows how to get only 'Active' players from the 'Players' relation. ```php namespace App\Model; use SilverStripe\ORM\DataObject; class Team extends DataObject { private static $has_many = [ 'Players' => Player::class, ]; public function getActivePlayers() { return $this->Players()->filter('Status', 'Active'); } // ... ``` -------------------------------- ### Access Class Configuration in PHP Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/04_Configuration/00_Configuration.md Retrieve configuration values set in YAML or other sources using the `config()->get()` method in PHP. This example shows how to access boolean and array configurations. ```php use App\MyClass; // prints false echo MyClass::config()->get('option_one'); // prints 'Foo, Bar, Baz' echo implode(', ', MyClass::config()->get('option_two')); ``` -------------------------------- ### Default HTTP Application Setup Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/16_Execution_Pipeline/03_App_Object_and_Kernel.md Sets up the default HTTP application, including the kernel, middleware, and request handling. This is typically found in your web root's index.php. ```php use SilverStripe\Control\HTTPApplication; use SilverStripe\Control\HTTPRequestBuilder; use SilverStripe\Core\CoreKernel; use SilverStripe\Core\Startup\ErrorControlChainMiddleware; require __DIR__ . '/vendor/autoload.php'; // Build request and detect flush $request = HTTPRequestBuilder::createFromEnvironment(); // Default application $kernel = new CoreKernel(BASE_PATH); $app = new HTTPApplication($kernel); $app->addMiddleware(new ErrorControlChainMiddleware($app)); $response = $app->handle($request); $response->output(); ``` -------------------------------- ### Registering and Getting Services with Injector Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Demonstrates how to register a service implementation for a given class and then retrieve an instance of that service using the Injector. This allows for runtime swapping of service implementations. ```php use App\MyClient; use SilverStripe\Core\Injector\Injector; // A default client singleton is created and registered - could be in core code Injector::inst()->registerService(new ReadClient(), MyClient::class); $client = Injector::inst()->get(MyClient::class); // $client is an instance of ReadClient // somewhere later, perhaps in some application code, a new singleton is registered to replace the old one Injector::inst()->registerService(new WriteClient(), MyClient::class); $client = Injector::inst()->get(MyClient::class); // $client is now an instance of WriteClient ``` -------------------------------- ### Equivalent of Repeated Entwine Calls Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/11_jQuery_Entwine.md This code demonstrates the equivalent of the previous example, showing how to achieve repeated method calls by first getting the Entwine object and then calling the method multiple times. ```javascript const div = $('div').entwine('foo'); div.bar(); div.bar(); div.bar(); ``` -------------------------------- ### Shortcode Syntax Examples Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/04_Shortcodes.md Illustrates various valid syntaxes for shortcodes, including simple tags, legacy closing slashes, parameters, and enclosed content. ```text # The most simple shortcodes don't need any parameters or wrap any content [my_shortcode] # A closing slash is allowed for legacy reasons [my_shortcode /] # Parameters can be included like so: [my_shortcode,myparameter="value"] # If you wrap any content in a shortcode, you need to have a closing tag [my_shortcode,myparameter="value"]Enclosed Content[/my_shortcode] ``` -------------------------------- ### Define URL Handlers for API Endpoints Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/02_Controllers/07_CMS_JSON_APIs.md Use the `url_handlers` configuration to map HTTP methods and URL segments to controller methods. This example shows how to create a GET endpoint for viewing a specific record using `$ItemID`. ```php namespace App\Controllers; use SilverStripe\Admin\AdminController; use SilverStripe\Control\HTTPResponse; class MySomethingController extends AdminController { // ... private static array $url_handlers = [ 'GET view/$ItemID' => 'apiView', ]; private static array $allowed_actions = [ 'apiView', ]; public function apiView(): HTTPResponse { $itemID = $request->param('ItemID'); // Note: would normally validate that $itemID is a valid integer and that $obj exists $obj = MyDataObject::get()->byID($itemID); $data = ['ID' => $obj->ID, 'Title' => $obj->Title]; return $this->jsonSuccess(200, $data); } } ``` -------------------------------- ### Create a new Player record Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md Instantiate a new DataObject using the `create()` method. This is preferred over `new` for dependency injection capabilities. ```php $player = Player::create(); ``` -------------------------------- ### React Component Example (JSX) Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/12_ReactJS_and_Redux.md Illustrates a basic React component using JSX syntax. This is the recommended way to express components. ```javascript import React from 'react'; // ... ; ``` -------------------------------- ### Standard Injector Instantiation Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Shows the standard, more verbose syntax for creating objects and fetching singletons directly through the Injector. ```php use App\MyClass; use SilverStripe\Core\Injector\Injector; // instantiate a new instance of App\MyClass via Injector $object = Injector::inst()->create(MyClass::class); // or fetch App\MyClass as a singleton $singletonObject = Injector::inst()->get(MyClass::class); ``` -------------------------------- ### Build the Silverstripe Database Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/index.md Run the Sake command to build your database schema after configuring the .env file. This command initializes the database for your Silverstripe project. ```bash vendor/bin/sake db:build ``` -------------------------------- ### Example Form Controller Implementation Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/03_Forms/00_Introduction.md Demonstrates a practical implementation of a controller method to create and return a Form instance with a text field, a submit action, and a required field validator. ```php // app/src/PageType/MyFormPageController.php namespace App\PageType; use PageController; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\Form; use SilverStripe\Forms\FormAction; use SilverStripe\Forms\TextField; use SilverStripe\Forms\Validation\RequiredFieldsValidator; class MyFormPageController extends PageController { private static $allowed_actions = [ 'getHelloForm', ]; private static $url_handlers = [ 'HelloForm' => 'getHelloForm', ]; public function getHelloForm() { $fields = FieldList::create( TextField::create('Name', 'Your Name') ); $actions = FieldList::create( FormAction::create('doSayHello')->setTitle('Say hello') ); $required = RequiredFieldsValidator::create('Name'); $form = Form::create($this, 'HelloForm', $fields, $actions, $required); return $form; } public function doSayHello($data, Form $form) { $form->sessionMessage('Hello ' . $data['Name'], 'success'); return $this->redirectBack(); } } ``` -------------------------------- ### Get a singleton object with Injector Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Use Injector::inst()->get() to retrieve a singleton instance of a specified class. Subsequent calls to get() for the same class will return the same object instance. ```php use App\MyClient; use SilverStripe\Core\Injector\Injector; // Fetches MyClient as a singleton $object = Injector::inst()->get(MyClient::class); $object2 = Injector::inst()->get(MyClient::class); // resolves to true $object === $object2; ``` -------------------------------- ### Controller Action Examples Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/02_Controllers/01_Introduction.md Demonstrates different ways controller actions can return responses, including creating new responses, modifying existing ones, rendering custom HTML, and returning JSON. ```php namespace App\Control; use SilverStripe\Control\Controller; // ... class TeamController extends Controller { // ... /** * Return some additional data to the current response that is waiting to go out, this makes $Title set to * 'My Team Name' and continues on with generating the response. */ public function index(HTTPRequest $request) { // ... } /** * We can manually create a response and return that to ignore any previous data or modifications to the request. */ public function someaction(HTTPRequest $request) { $this->setResponse(new HTTPResponse()); $this->getResponse()->setStatusCode(400); $this->getResponse()->setBody('invalid'); return $this->getResponse(); } /** * Or, we can modify the response that is waiting to go out. */ public function anotheraction(HTTPRequest $request) { $this->getResponse()->setStatusCode(400); return $this->getResponse(); } /** * We can render HTML and leave Silverstripe CMS to set the response code and body. */ public function htmlaction() { return $this->customise(ArrayData::create([ 'Title' => 'HTML Action', ]))->renderWith('MyCustomTemplate'); } /** * We can send stuff to the browser which isn't HTML */ public function ajaxaction() { $this->getResponse()->addHeader('Content-type', 'application/json'); return json_encode([ 'json' => true, ]); } } ``` -------------------------------- ### Manually Create and Write DataObjects Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/06_Testing/04_Fixtures.md Demonstrates how to programmatically create and write DataObjects, equivalent to what YAML fixtures do. ```php use App\Test\Team; $team = Team::create([ 'Name' => 'Hurricanes', 'Origin' => 'Wellington', ]); $team->write(); $team->Players()->add($john); ``` -------------------------------- ### Not Starts With Filter Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/00_Model/06_SearchFilters.md Fetches players whose first name does NOT start with 'S'. Uses the ':StartsWith:not' modifier. ```php // use :not to get everyone whose first name does NOT start with "S" $players = Player::get()->filter([ 'FirstName:StartsWith:not' => 'S', ]); ``` -------------------------------- ### Handle Variadic Parameters with $* in StaffController Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/02_Controllers/02_Routing.md Uses the $* wildcard to match all remaining URL parameters without collecting them into numbered arguments. Use remaining() to get all, shift() to get and remove the next, or shift(n) to get and remove n parameters. ```php namespace App\Control; use SilverStripe\Control\Controller; use SilverStripe\Control\HTTPRequest; class StaffController extends Controller { private static $url_handlers = [ '$*' => 'index', ]; public function index(HTTPRequest $request) { // GET /staff/managers/bob/hobbies // "managers/bob/hobbies" $request->remaining(); // returns "managers", and removes that from the list of remaining params $nextParam = $request->shift(); // returns ["bob", "hobbies"] and removes those from the list of remaining params $moreParams = $request->shift(2); } } ``` -------------------------------- ### Instantiate Controller and Access Dependencies Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Get an instance of MyController using Injector and access its configured properties. This demonstrates how the dependencies defined in the class are resolved and assigned. ```php use App\Control\MyController; use SilverStripe\Core\Injector\Injector; $object = Injector::inst()->get(MyController::class); // prints 'ThirdParty\PermissionService' echo get_class($object->permissions); // prints 'This will just be assigned as a string' echo $object->getDefaultText(); ``` -------------------------------- ### Get all Player records Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md Retrieve a `DataList` containing all records of a specific DataObject class using the `get()` method. ```php // returns a `DataList` containing all the `Player` objects. $players = Player::get(); ``` -------------------------------- ### Create a Development Project with Composer Source: https://github.com/silverstripe/developer-docs/blob/6/en/00_Getting_Started/02_Composer.md This command sets up a new Silverstripe CMS project for development, keeping full version control history and including developer requirements. Use the appropriate branch (e.g., `6.x-dev`) for your needs. ```bash composer create-project --keep-vcs silverstripe/installer ./my-project 6.x-dev --prefer-source ``` -------------------------------- ### Install Yarn Globally Source: https://github.com/silverstripe/developer-docs/blob/6/en/10_Contributing/06_Build_Tooling.md Installs the Yarn package manager globally using npm. This is a prerequisite for managing JavaScript dependencies. ```bash npm install -g yarn ``` -------------------------------- ### Install silverstripe/mimevalidator module Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/14_Files/06_Allowed_file_types.md Install the MIME type validation module using Composer. This is required to enable MIME type validation. ```bash composer require silverstripe/mimevalidator ``` -------------------------------- ### Convenient Object Instantiation with Injectable Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/05_Injector.md Demonstrates the convenient syntax for creating and fetching singletons using the `Injectable` trait. ```php use App\MyClass; // instantiate a new instance of App\MyClass via Injector $object = MyClass::create(); // or fetch App\MyClass as a singleton $singletonObject = MyClass::singleton(); ``` -------------------------------- ### Perform GET Request Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/06_Testing/01_Functional_Testing.md Performs a GET request on a given URL and retrieves the HTTPResponse. This also updates the current page context. ```php $page = $this->get($url); ``` -------------------------------- ### Case-Insensitive Starts With Filter Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/00_Model/06_SearchFilters.md Fetches players whose first name starts with 'S', ignoring case. Uses the ':StartsWith:nocase' modifier. ```php $players = Player::get()->filter([ 'FirstName:StartsWith:nocase' => 'S', ]); ``` -------------------------------- ### Template Formatting Examples Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/01_Templates/09_Casting.md Demonstrates calling methods on template variables to format data. This includes accessing specific parts of content like the first paragraph or formatting dates. ```ss <%-- app/src/Page.ss --%> <%-- prints the result of DBHtmlText::FirstParagragh() --%> $Content.FirstParagraph <%-- prints the result of DBDatetime::Format("d/m/Y") --%> $LastEdited.Format("d/m/Y") ``` ```ss <%-- prints the first paragraph of content for the first item in the list --%> $MyList.First.Content.FirstParagraph <%-- prints "Copyright 2023" --%>

Copyright {$Now.Year}

<%-- prints
--%>
``` -------------------------------- ### Redux Reducer and Store Example Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/12_ReactJS_and_Redux.md Demonstrates a simple Redux reducer function for state mutation and how to create and interact with a Redux store. ```javascript // reducer function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } const store = createStore(counter); // subscribe to an action store.subscribe(() => { const state = store.g.etState(); // ... do something with the state here }); // Call an action - in this case increment the state from 0 to 1 store.dispatch({ type: 'INCREMENT' }); ``` -------------------------------- ### Example PJAX AJAX HTTP Response Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/04_CMS_Architecture.md This is an example of an abbreviated JSON response from the server, containing the updated PJAX fragments keyed by their fragment names. ```json {"MyRecordInfo": "getOption('do-action')) { $output->writeln('Doing something...'); } return Command::SUCCESS; } public function getOptions(): array { return [ new InputOption('do-action', null, InputOption::VALUE_NONE, 'do something specific'), ]; } } ``` -------------------------------- ### Create New Tab Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/03_Forms/06_Tabbed_Forms.md This demonstrates how to create a new tab and add fields to it. ```php $fields->addFieldToTab('Root.MyNewTab', TextField::create(/* ... */)); ``` -------------------------------- ### Create and Get Services with Injector Source: https://context7.com/silverstripe/developer-docs/llms.txt Use the Injector to create new instances of services or retrieve singletons. Constructor arguments can be passed during creation. ```php use App\Service\EmailService; use SilverStripe\Core\Injector\Injector; // Create a new instance each time $service = Injector::inst()->create(EmailService::class); // Singleton (same instance on repeated calls) $singleton = Injector::inst()->get(EmailService::class); // Pass constructor args $service = Injector::inst()->create(EmailService::class, 'arg1', 'arg2'); ``` -------------------------------- ### Database Schema for Product Inheritance Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/00_Model/01_Data_Model_and_ORM.md Illustrates the database schema for the Product and its subclass Computer, showing how fields are distributed across tables based on class definitions. ```yml Product: ID: Int ClassName: Enum('Sport', 'BallSport', 'Tennis') Created: Datetime LastEdited: Datetime SKU: Text Product_Digital_Computer: ID: Int IsPreBuilt: 'Boolean' ``` -------------------------------- ### CMS Panel Layout Example Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/15_Customising_the_Admin_Interface/05_CMS_Layout.md Use the data-layout-type attribute on CMS panels to define how their children are laid out. This example uses 'border' layout for a content toolbar. ```html
``` -------------------------------- ### Member Class Extension Hook Example Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/01_Extensions.md This example shows how the `Member` class uses an extension hook `updateValidator` to allow extensions to modify the validator object. ```php namespace SilverStripe\Security; use SilverStripe\ORM\DataObject; // ... class Member extends DataObject { // ... public function getValidator() { // ... $this->extend('updateValidator', $validator); // ... } // ... } ``` -------------------------------- ### Install a Silverstripe Module using Composer Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/05_Extending/00_Modules.md Use the Composer package manager to install modules into your Silverstripe CMS project. This command fetches the latest compatible stable version. ```bash composer require silverstripe/linkfield ``` -------------------------------- ### Configure Primary and Read-only Database Replicas Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/08_Performance/08_Read_only_database_replicas.md Define environment variables for the primary database and its read-only replicas. Replicas are suffixed with _REPLICA_, starting from 01. Certain configurations like SS_DATABASE_CLASS and SS_DATABASE_NAME cannot be defined per replica. ```bash # Primary database SS_DATABASE_CLASS="MySQLDatabase" SS_DATABASE_SERVER="my-db-server" SS_DATABASE_PORT="3306" SS_DATABASE_USERNAME="my-user" SS_DATABASE_PASSWORD="my-password" SS_DATABASE_NAME="db" # Read-only replica SS_DATABASE_SERVER_REPLICA_01="my-db-replica" SS_DATABASE_PORT_REPLICA_01="3306" SS_DATABASE_USERNAME_REPLICA_01="my-replica-user" SS_DATABASE_PASSWORD_REPLICA_01="my-replica-password" ``` -------------------------------- ### Get Uninherited Configuration Properties Source: https://github.com/silverstripe/developer-docs/blob/6/en/02_Developer_Guides/04_Configuration/00_Configuration.md Retrieve configuration property values only if they are defined for the specific class, using either Config::inst()->uninherited() or config()->get('property', Config::UNINHERITED). ```php Config::inst()->uninherited(MyClass::class, 'property'); ``` ```php MyClass::config()->get('property', Config::UNINHERITED); ``` -------------------------------- ### Create a Working Branch Source: https://github.com/silverstripe/developer-docs/blob/6/en/10_Contributing/01_Code.md Checkout the correct base branch (e.g., '6.1') and then create a new branch for your work. Use a descriptive name for your branch. ```bash # make sure you're starting from the correct branch first cd vendor// git checkout --track origin/6.1 # then create your working branch git checkout -b ```