### Setup and Teardown for Each Test Source: https://docs.silverstripe.org/en/6/developer_guides/testing/unit_testing Use setUp() and tearDown() methods to perform actions before and after each test method. This example demonstrates creating pages and setting configuration. ```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() { // ... } } ``` -------------------------------- ### Example File Structure Source: https://docs.silverstripe.org/en/6/contributing/documentation Illustrates a typical directory structure for documentation files, including how to organize how-to guides and main content. ```text 00_Model/ ├─ How_Tos ├─ Dynamic_Default_Fields.md ├─ Grouping_DataObject_Sets.md └─ index.md ├─ 00_Data_Model_and_ORM.md ├─ 01_Relations.md ├─ ... └─ index.md ``` -------------------------------- ### Common Sake Commands Source: https://docs.silverstripe.org/en/6/developer_guides/cli/sake Examples of frequently used Sake commands for listing commands, tasks, building the database, flushing the cache, and getting help. ```bash # list available commands sake # or `sake list` # list available tasks sake tasks # build the database sake db:build # flush the cache sake flush # or use the `--flush` flag with any command # get help info about a command (including tasks) sake --help # e.g. `sake db:build --help` ``` -------------------------------- ### Example Configuration File Source: https://docs.silverstripe.org/en/6/optional_features/graphql/getting_started/configuring_your_schema An example of a configuration file within the app/_graphql/config directory. ```yaml # app/_graphql/config/config.yml # my config here ``` -------------------------------- ### Install and use Node.js with nvm Source: https://docs.silverstripe.org/en/6/contributing/build_tooling Installs and uses the recommended version of Node.js via Node Version Manager (nvm). Ensure nvm is installed first. ```bash nvm install && nvm use ``` -------------------------------- ### Define a Custom Queued Job with Steps Source: https://docs.silverstripe.org/en/6/optional_features/queuedjobs/defining-jobs This example demonstrates how to create a custom queued job by extending `AbstractQueuedJob`. It includes methods for initialization (`setup`), processing individual items (`process`), and reporting progress. Use this pattern for jobs that process a list of items, where each item represents a step. ```php namespace App\Jobs; use Symbiote\QueuedJobs\Services\AbstractQueuedJob; /** * Class MyJob * * @property array $items * @property array $remaining */ class MyJob extends AbstractQueuedJob { public function hydrate(array $items): void { $this->items = $items; } public function getTitle(): string { return 'My awesome job'; } public function setup(): void { $this->remaining = $this->items; $this->totalSteps = count($this->items); } public function process(): void { $remaining = $this->remaining; // check for trivial case if (count($remaining) === 0) { $this->isComplete = true; return; } $item = array_shift($remaining); // code that will process your item goes here // update job progress $this->remaining = $remaining; $this->currentStep += 1; // check for job completion if (count($remaining) > 0) { return; } $this->isComplete = true; } } ``` -------------------------------- ### Install Login Forms Module Source: https://docs.silverstripe.org/en/6/optional_features/login-forms Install the login-forms module using Composer. ```bash composer require silverstripe/login-forms ``` -------------------------------- ### Install Static Publish Queue Module Source: https://docs.silverstripe.org/en/6/optional_features/staticpublishqueue Install the staticpublishqueue module using Composer. ```bash composer require silverstripe/staticpublishqueue ``` -------------------------------- ### Create Project with Latest Unstable Installer Source: https://docs.silverstripe.org/en/6/getting_started/composer Use this command to start a new Silverstripe project based on the latest unstable version of the silverstripe/installer. This is useful for contributing to the CMS or getting early access to changes. ```bash composer create-project silverstripe/installer ./my-project 6.x-dev ``` -------------------------------- ### Example Models File Source: https://docs.silverstripe.org/en/6/optional_features/graphql/getting_started/configuring_your_schema An example of a models file within the app/_graphql/models directory. ```yaml # app/_graphql/models/models.yml # my models here ``` -------------------------------- ### Get Prototype Service Instance Source: https://docs.silverstripe.org/en/6/developer_guides/extending/injector Demonstrates that requesting a 'prototype' service using `get()` will always instantiate a new object, even though `get()` typically returns singletons. ```php use App\MyClient; use SilverStripe\Core\Injector\Injector; // Instantiates new MyClient objects each time, even though this would normally fetch a singleton $object = Injector::inst()->get(MyClient::class); $object2 = Injector::inst()->get(MyClient::class); // resolves to false $object === $object2; ``` -------------------------------- ### Example Types File Source: https://docs.silverstripe.org/en/6/optional_features/graphql/getting_started/configuring_your_schema An example of a types file within the app/_graphql/types directory. ```yaml # app/_graphql/types/types.yml # my types here ``` -------------------------------- ### Install Silverstripe GraphQL Source: https://docs.silverstripe.org/en/6/optional_features/graphql Install the silverstripe/graphql package using Composer. ```bash composer require silverstripe/graphql ``` -------------------------------- ### Install Dependencies and Lint Documentation Source: https://docs.silverstripe.org/en/6/contributing/documentation Run these commands to install necessary dependencies and lint the documentation locally. Use the `--fix` option to automatically resolve fixable linting issues. ```bash yarn install composer install yarn lint ``` ```bash yarn lint --fix ``` -------------------------------- ### Install Silverstripe MFA Module Source: https://docs.silverstripe.org/en/6/optional_features/mfa Use Composer to install the silverstripe/mfa module. ```bash composer require silverstripe/mfa ``` -------------------------------- ### Full Example index.php with Static Handler Source: https://docs.silverstripe.org/en/6/optional_features/staticpublishqueue/handling-requests A complete `index.php` example demonstrating how to integrate the static request handler. It includes autoloading, cache checking, and fallback to Silverstripe CMS for requests not served statically. ```php use SilverStripe\Control\HTTPApplication; use SilverStripe\Control\HTTPRequestBuilder; use SilverStripe\Core\CoreKernel; // Find autoload.php if (file_exists(__DIR__ . '/vendor/autoload.php')) { require __DIR__ . '/vendor/autoload.php'; } elseif (file_exists(__DIR__ . '/../vendor/autoload.php')) { require __DIR__ . '/../vendor/autoload.php'; } else { header('HTTP/1.1 500 Internal Server Error'); echo 'autoload.php not found'; exit(1); } $requestHandler = require 'staticrequesthandler.php'; // successful cache hit if ($requestHandler('cache') !== false) { die; } header('X-Cache-Miss: ' . date(Datetime::COOKIE)); // Build request and detect flush $request = HTTPRequestBuilder::createFromEnvironment(); // Default application $kernel = new CoreKernel(BASE_PATH); $app = new HTTPApplication($kernel); $response = $app->handle($request); $response->output(); ``` -------------------------------- ### Example Bulk Loader File Source: https://docs.silverstripe.org/en/6/optional_features/graphql/getting_started/configuring_your_schema An example of a bulk loader file within the app/_graphql/bulkLoad directory. ```yaml # app/_graphql/bulkLoad/bulkLoad.yml # my bulk loader directives here ``` -------------------------------- ### Install UserForms Module Source: https://docs.silverstripe.org/en/6/optional_features/userforms Install the SilverStripe UserForms module using Composer. ```bash composer require silverstripe/userforms ``` -------------------------------- ### Example Enums File Source: https://docs.silverstripe.org/en/6/optional_features/graphql/getting_started/configuring_your_schema An example of an enums file within the app/_graphql/enums directory. ```yaml # app/_graphql/enums/enums.yml # my enums here ``` -------------------------------- ### Install Dependencies and Run Pattern Library Locally Source: https://docs.silverstripe.org/en/6/developer_guides/customising_the_admin_interface/cms_architecture Install project dependencies and run the pattern library locally. This requires a Silverstripe CMS project and yarn. Ensure JS source files are included by using the '--prefer-source' flag with Composer. ```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 ``` -------------------------------- ### Registering an Identity Store (LDAP Example) Source: https://docs.silverstripe.org/en/6/developer_guides/security/authentication Register a custom identity store, like an LDAP authenticator, and configure its settings and handler. This example shows how to set LDAP settings and cascade into session authentication. ```yaml SilverStripe\Core\Injector\Injector: App\LDAP\Authenticator\LDAPAuthenticator: properties: LDAPSettings: - URL: https://my-ldap-location.com CascadeInTo: '%$SilverStripe\Security\MemberAuthenticator\SessionAuthenticationHandler' SilverStripe\Security\AuthenticationHandler: class: SilverStripe\Security\RequestAuthenticationHandler properties: Handlers: ldap: '%$App\LDAP\Authenticator\LDAPAuthenticator' ``` -------------------------------- ### Basic Dependency Injection Example Source: https://docs.silverstripe.org/en/6/developer_guides/customising_the_admin_interface/reactjs_and_redux A simple example of using the `inject` HOC to make 'Dependency1' and 'Dependency2' available as props to `MyComponent`. ```javascript const MyInjectedComponent = inject( ['Dependency1', 'Dependency2'] )(MyComponent); // MyComponent now has access to props.Dependency1 and props.Dependency2 ``` -------------------------------- ### Bulk Load Configuration Example Source: https://docs.silverstripe.org/en/6/optional_features/graphql/working_with_dataobjects/adding_dataobjects_to_the_schema Define groups of directives to load a bundle of classes and apply the same configuration to all of them. This example shows loading elemental blocks and models with the Versioned extension. ```yaml # app/_graphql/bulkLoad.yml elemental: # An arbitrary key to define what these directives are doing # Load all elemental blocks except MySecretElement load: inheritanceLoader: include: - DNADesign\Elemental\Models\BaseElement exclude: - App\Model\Elemental\MySecretElement # Add all fields and read operations apply: fields: '*': true operations: read: true readOne: true app: # Load everything in our App\Model\ namespace that has the Versioned extension # unless the filename ends with .secret.php load: namespaceLoader: include: - App\Model\* extensionLoader: include: - SilverStripe\Versioned\Versioned filepathLoader: exclude: - app/src/Model/*.secret.php apply: fields: '*': true operations: '*': true ``` -------------------------------- ### Install Silverstripe CMS using Composer Source: https://docs.silverstripe.org/en/6/getting_started Use this command to create a new Silverstripe project. Ensure you have Composer installed. ```bash composer create-project silverstripe/installer my-project ``` -------------------------------- ### Install dependencies with Composer Source: https://docs.silverstripe.org/en/6/getting_started/composer Use `composer install` to install dependencies based on the `composer.lock` file for reproducible builds. For production, use `--no-dev` to exclude development dependencies and `-o` to optimize the autoloader for speed. ```bash composer install --no-dev -o ``` -------------------------------- ### Install TinyMCE Module Source: https://docs.silverstripe.org/en/6/optional_features/htmleditor-tinymce Install the TinyMCE module using Composer. This is the initial step to integrate the editor. ```bash composer require silverstripe/htmleditor-tinymce ``` -------------------------------- ### Example Tags for Branching Strategy Source: https://docs.silverstripe.org/en/6/project_governance/repository_management Illustrates existing tags to understand the context for branch naming conventions. These examples help determine which branches are for patch, minor, or major releases. ```text 1.1.17 1.2.0 ``` -------------------------------- ### Install Silverstripe CMS Project Source: https://docs.silverstripe.org/en/6/contributing/code Use this command to create a new Silverstripe project installation. Specify the desired version branch (e.g., 6.1.x-dev). ```bash composer create-project --keep-vcs silverstripe/installer ./your-website-folder 6.1.x-dev ``` -------------------------------- ### Install TOTP Authenticator Module Source: https://docs.silverstripe.org/en/6/optional_features/totp-authenticator Install the TOTP authenticator module using Composer. ```bash composer require silverstripe/totp-authenticator ``` -------------------------------- ### YAML Fixture Example Source: https://docs.silverstripe.org/en/6/developer_guides/testing/fixtures Example of defining Player and Team data in YAML format for fixtures. ```yaml App\Test\Team: team1: Name: 'The Avengers' Origin: 'Earth' team2: Name: 'Justice League' Origin: 'Earth' App\Test\Player: player1: Name: 'Iron Man' Team: =>App\Test\Team.team1 player2: Name: 'Captain America' Team: =>App\Test\Team.team1 player3: Name: 'Superman' Team: =>App\Test\Team.team2 ``` -------------------------------- ### Install Module from GitHub using Composer Source: https://docs.silverstripe.org/en/6/developer_guides/extending/modules Use this command to install a module directly from a GitHub repository, ensuring local development files are kept. Adjust the branch name (e.g., 'dev-main') as needed. ```bash composer require my_vendor/module_name:dev-main --prefer-source ``` -------------------------------- ### Install Silverstripe Fluent with Composer Source: https://docs.silverstripe.org/en/6/optional_features/fluent/installation Use this command to add the Fluent module to your Silverstripe project via Composer. After installation, run `dev/build?flush=1`, configure locales in the admin area, and publish pages. ```bash composer require tractorcow/silverstripe-fluent ``` -------------------------------- ### Install GridField Bulk Editing Tools Source: https://docs.silverstripe.org/en/6/optional_features/gridfield-bulk-editing-tools Install the GridField bulk editing tools module using Composer. ```bash composer require colymba/gridfield-bulk-editing-tools ``` -------------------------------- ### Install JavaScript dependencies Source: https://docs.silverstripe.org/en/6/contributing/build_tooling Installs all JavaScript dependencies defined in package.json. Run this command in the root of the silverstripe/admin module and any other modules you are working on. ```bash yarn install ``` -------------------------------- ### Start Tika REST Server Source: https://docs.silverstripe.org/en/6/optional_features/textextraction/tika Command to start the Tika REST server. This command should be run in your terminal to make the Tika service available to Silverstripe. ```bash java -jar tika-server-1.8.jar --host=localhost --port=9998 ``` -------------------------------- ### HTTPApplication Setup and Middleware Source: https://docs.silverstripe.org/en/6/developer_guides/execution_pipeline/app_object_and_kernel Instantiate an HTTPApplication, add middleware like ErrorControlChainMiddleware, and handle an incoming HTTP request. ```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(); ``` -------------------------------- ### Example DataObject with Custom Indexes Source: https://docs.silverstripe.org/en/6/developer_guides/model/indexes A practical example of defining a custom composite index named 'MyIndexName' on 'MyField' and 'MyOtherField' within a DataObject. This setup helps optimize queries involving these two fields. ```php // app/src/MyTestObject.php namespace App\Model; use SilverStripe\ORM\DataObject; class MyTestObject extends DataObject { private static array $db = [ 'MyField' => 'Varchar', 'MyOtherField' => 'Varchar', ]; private static array $indexes = [ 'MyIndexName' => ['MyField', 'MyOtherField'], ]; } ``` -------------------------------- ### Build the Database Source: https://docs.silverstripe.org/en/6/getting_started Run this command to initialize your database schema after configuring the .env file. This command uses the Sake tool. ```bash vendor/bin/sake db:build ``` -------------------------------- ### Process Jobs with `lsyncd` Configuration Source: https://docs.silverstripe.org/en/6/optional_features/queuedjobs/immediate-jobs Configure `lsyncd` to monitor a directory for changes and execute the `ProcessJobQueueTask`. This example shows a typical `/etc/lsyncd.conf` setup. ```bash -- Queue Processor configuration, typically placed in /etc/lsyncd.conf settings = { logfile = "/var/log/lsyncd/lsyncd.log", statusFile = "/var/run/lsyncd.status", nodaemon = true, } -- Define the command and path for the each system being monitored here, where webuser is the user your webserver -- runs as runcmd = "/sbin/runuser webuser -c \"/usr/bin/php /var/www/sitepath/vendor/bin/sake tasks:ProcessJobQueueTask job=\"$1\" /var/www/sitepath/framework/silverstripe-cache/queuedjobs\"" site_processor = { onCreate = function(event) log("Normal", "got an onCreate Event") spawnShell(event, runcmd, event.basename) end, } sync{site_processor, source="/var/www/sitepath/silverstripe-cache/queuedjobs"} ``` -------------------------------- ### Immutable State Update Example Source: https://docs.silverstripe.org/en/6/developer_guides/customising_the_admin_interface/reactjs_and_redux Demonstrates how to update state immutably using spread syntax or Object.assign. ```javascript newProps = { ...oldProps, name: 'New name' }; ``` ```javascript newProps = Object.assign( {}, oldProps, { name: 'New name' } ); ``` -------------------------------- ### PJAX AJAX Request Header Source: https://docs.silverstripe.org/en/6/developer_guides/customising_the_admin_interface/cms_architecture An example of an abbreviated AJAX HTTP GET request sent by the client, specifying the desired PJAX fragments ('MyRecordInfo', 'Breadcrumbs') via the `X-Pjax` header. ```text GET /admin/myadmin HTTP/1.1 X-Pjax:MyRecordInfo,Breadcrumbs X-Requested-With:XMLHttpRequest ``` -------------------------------- ### Setup and Teardown Once Per Class Source: https://docs.silverstripe.org/en/6/developer_guides/testing/unit_testing Utilize setUpBeforeClass() and tearDownAfterClass() for actions that should run only once for the entire test class. Remember to call 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(); // ... } // ... } ``` -------------------------------- ### Create Custom Filtered Relation Lists Source: https://docs.silverstripe.org/en/6/developer_guides/model/relations Create custom relation lists with filtered results without writing raw SQL. This example shows how to get only 'Active' players from a 'Players' relation on a 'Team' object. ```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'); } // ... } ``` -------------------------------- ### Configure Environment Variables Source: https://docs.silverstripe.org/en/6/getting_started Set up your database credentials and admin user details in the .env file. Replace placeholders with your specific information. ```bash SS_DATABASE_CLASS="MySQLDatabase" SS_DATABASE_NAME="" SS_DATABASE_SERVER="localhost" SS_DATABASE_USERNAME="" SS_DATABASE_PASSWORD="" SS_DEFAULT_ADMIN_USERNAME="admin" SS_DEFAULT_ADMIN_PASSWORD="password" SS_ENVIRONMENT_TYPE="" ``` -------------------------------- ### Implement GridField Custom Action with Action Menu Integration Source: https://docs.silverstripe.org/en/6/developer_guides/forms/how_tos/create_a_gridfield_actionprovider Provides a comprehensive example of a custom GridField action class that implements GridField_ActionMenuItem for integration with the action menu dropdown. It includes methods for getting the action title, extra data for the frontend, and group assignment. ```php namespace App\Form\GridField; use SilverStripe\Forms\GridField\AbstractGridFieldComponent; use SilverStripe\Forms\GridField\GridField_ActionMenuItem; use SilverStripe\Forms\GridField\GridField_ActionProvider; use SilverStripe\Forms\GridField\GridField_ColumnProvider; use SilverStripe\Forms\GridField\GridField_FormAction; class GridFieldCustomAction extends AbstractGridFieldComponent implements GridField_ColumnProvider, GridField_ActionProvider, GridField_ActionMenuItem { public function getTitle($gridField, $record, $columnName) { return 'Custom action'; } public function getExtraData($gridField, $record, $columnName) { $field = $this->getCustomAction($gridField, $record); if ($field) { return array_merge($field->getAttributes(), [ 'classNames' => 'action-detail', 'icon' => 'circle-star', ]); } return []; } public function getGroup($gridField, $record, $columnName) { return GridField_ActionMenuItem::DEFAULT_GROUP; } public function getColumnContent() { return $this->getCustomAction()?->Field(); } private function getCustomAction($gridField, $record) { if (!$record->hasMethod('canEdit') || !$record->canEdit()) { return; } return GridField_FormAction::create( $gridField, 'CustomAction' . $record->ID, 'Custom action', 'docustomaction', ['RecordID' => $record->ID] )->addExtraClass( 'action-menu--handled btn btn-outline-dark' ); } // ... } ``` -------------------------------- ### Install Silverstripe Taxonomy Module Source: https://docs.silverstripe.org/en/6/optional_features/taxonomies Use Composer to install the silverstripe/taxonomy module. Ensure your Silverstripe CMS installation is compatible. ```bash composer require silverstripe/taxonomy ``` -------------------------------- ### Get a Singleton Object Instance Source: https://docs.silverstripe.org/en/6/developer_guides/extending/injector Use the `get` method to retrieve a singleton instance of a class. Subsequent calls to `get` for the same class will return the same object. ```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; ``` -------------------------------- ### Example Pagination Query Source: https://docs.silverstripe.org/en/6/optional_features/graphql/working_with_dataobjects/query_plugins Demonstrates how to use the pagination plugin to fetch a limited and offset list of nodes, including edges and page information. ```graphql query { readPages(limit: 10, offset: 20) { nodes { title } edges { node { title } } pageInfo { totalCount hasNextPage hasPrevPage } } } ``` -------------------------------- ### Get All Cookies Source: https://docs.silverstripe.org/en/6/developer_guides/cookies_and_sessions/cookies Retrieve all cookies. Use the first method to get cookies set during the current process and subsequent requests. Use the second method to get only cookies from the current request. ```php //returns all the cookies including ones set during the current process Cookie::get_inst()->getAll(); ``` ```php //returns all the cookies in the request Cookie::get_inst()->getAll(false); ``` -------------------------------- ### Define Form Actions and Submit Handler Source: https://docs.silverstripe.org/en/6/developer_guides/forms/introduction This example demonstrates how to create a form with fields and actions, and defines the method to handle form submission. ```php namespace App\PageType; use PageController; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\Form; use SilverStripe\Forms\FormAction; class MyFormPageController extends PageController { private static $allowed_actions = [ 'getMyForm', ]; private static $url_handlers = [ 'MyForm' => 'getMyForm', ]; public function getMyForm() { $fields = FieldList::create(/* .. */); $actions = FieldList::create( FormAction::create('doSubmitForm', 'Submit') ); $form = Form::create($controller, 'MyForm', $fields, $actions); // Get the actions $actions = $form->Actions(); // As actions is a FieldList, push, insertBefore, removeByName and other // methods described for `Fields` also work for actions. $actions->push( FormAction::create('doSecondaryFormAction', 'Another Button') ); $actions->removeByName('doSubmitForm'); $form->setActions($actions); return $form } public function doSubmitForm($data, $form) { // ... } public function doSecondaryFormAction($data, $form) { // ... } } ``` -------------------------------- ### Configure Primary and Read-only Database Replicas Source: https://docs.silverstripe.org/en/6/developer_guides/performance/read_only_database_replicas Set up environment variables for both the primary database and its read-only replicas. Ensure replicas are numbered sequentially starting from 01. ```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" ``` -------------------------------- ### Populating a Default GraphQL Schema Source: https://docs.silverstripe.org/en/6/optional_features/graphql/getting_started/configuring_your_schema This example shows how to populate a pre-configured 'default' schema. It includes sections for general configuration, types, models, queries, mutations, and enums. ```yaml # app/_config/graphql.yml SilverStripe\GraphQL\Schema\Schema: schemas: default: config: # general schema config here types: # your generic types here models: # your DataObjects here queries: # your queries here mutations: # your mutations here enums: # your enums here ``` -------------------------------- ### Create a development environment with Composer Source: https://docs.silverstripe.org/en/6/getting_started/composer Set up a development environment for contributing to Silverstripe CMS by using `composer create-project` with the `--keep-vcs` flag and specifying a development version. This ensures full git repository information and includes developer requirements. ```bash composer create-project --keep-vcs silverstripe/installer ./my-project 6.x-dev --prefer-source ``` -------------------------------- ### Redux Reducer and Store Example Source: https://docs.silverstripe.org/en/6/developer_guides/customising_the_admin_interface/reactjs_and_redux Demonstrates a simple Redux reducer function for managing state changes and setting up a store. It shows how to subscribe to state updates and dispatch actions. ```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' }); ``` -------------------------------- ### Manage Daemon Processes with systemctl Source: https://docs.silverstripe.org/en/6/changelogs/6.0.0 The `sake -start` and `sake -stop` commands for managing daemon processes have been removed. Use a dedicated daemon tool like `systemctl` for process management. ```bash sake -start my-process systemctl start my-process.service ``` -------------------------------- ### Check Composer Installation Source: https://docs.silverstripe.org/en/6/getting_started/composer Verify that the Composer command is installed and accessible globally on your system. ```bash composer help ``` -------------------------------- ### YAML Configuration with Before/After Priorities Source: https://docs.silverstripe.org/en/6/developer_guides/configuration/configuration Illustrates how to use 'Before' and 'After' rules in the header to control the priority of a value set relative to others. ```yaml --- Name: adminroutes Before: '*' After: - '#rootroutes' --- SilverStripe\Control\Director: rules: 'admin': 'SilverStripe\Admin\AdminRootController' --- ``` -------------------------------- ### Configure File Ownership for Versioned DataObjects Source: https://docs.silverstripe.org/en/6/developer_guides/files/file_management PHP example demonstrating how to configure ownership of associated assets (e.g., Banner Image) from a parent record (e.g., LandingPage). ```php namespace App\PageType; use Page; use SilverStripe\Assets\Image; class LandingPage extends Page { private static $has_one = [ 'Banner' => Image::class, ]; private static $owns = ['Banner']; } ``` -------------------------------- ### File Shortcode Example Source: https://docs.silverstripe.org/en/6/developer_guides/files/file_management An example of an embedded image within HTML content using a shortcode. ```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"]

``` -------------------------------- ### Install TagField Module Source: https://docs.silverstripe.org/en/6/optional_features/tagfield Install the TagField module using Composer. This command adds the module to your Silverstripe project. ```bash composer require silverstripe/tagfield ``` -------------------------------- ### Set up Cron Job for Queued Jobs Source: https://docs.silverstripe.org/en/6/optional_features/queuedjobs/overview Install the cron job to manage system jobs. It's recommended to run this as the same user as your webserver to avoid file permission issues. ```bash */1 * * * * /path/to/silverstripe/vendor/bin/sake dev/tasks/ProcessJobQueueTask ``` -------------------------------- ### Install RealMe Module Source: https://docs.silverstripe.org/en/6/optional_features/realme Install the RealMe module using Composer. This command adds the module to your Silverstripe project. ```bash composer require silverstripe/realme ``` -------------------------------- ### GraphQL Query Response Example Source: https://docs.silverstripe.org/en/6/optional_features/graphql/working_with_generic_types/building_a_custom_query Example JSON response for the 'readCountries' GraphQL query, showing country data. ```json { "data": { "readCountries": [ { "name": "Afghanistan", "code": "af" }, { "name": "Åland Islands", "code": "ax" }, "... etc" ] } } ``` -------------------------------- ### Install Elemental Module Source: https://docs.silverstripe.org/en/6/optional_features/elemental Install the Elemental module using Composer. This command adds the necessary package to your Silverstripe project. ```bash composer require dnadesign/silverstripe-elemental ``` -------------------------------- ### React Component Example (JSX) Source: https://docs.silverstripe.org/en/6/developer_guides/customising_the_admin_interface/reactjs_and_redux Illustrates a basic React component using JSX syntax, which is transpiled into native JavaScript calls. This is the recommended way to express components. ```javascript import React from 'react'; // ... ; ``` -------------------------------- ### Install Text Extraction Module Source: https://docs.silverstripe.org/en/6/optional_features/textextraction Install the text extraction module using Composer. This command adds the necessary package to your project. ```bash composer require silverstripe/textextraction ``` -------------------------------- ### Using <% with %> for Scope and Direct Access Source: https://docs.silverstripe.org/en/6/developer_guides/templates/syntax Compares the use of the '<% with %>' tag for scope management against direct property access. The '<% with %>' example is shown to be cleaner and more readable. ```html <% with $CurrentMember %> Hello, $FirstName, welcome back. Your current balance is $Balance. <% end_with %> ``` ```html Hello, $CurrentMember.FirstName, welcome back. Your current balance is $CurrentMember.Balance ``` -------------------------------- ### Install GridField Extensions Source: https://docs.silverstripe.org/en/6/optional_features/gridfieldextensions Install the GridField extensions module using Composer. This command adds the necessary package to your Silverstripe project. ```bash composer require symbiote/silverstripe-gridfieldextensions ``` -------------------------------- ### Update Installed Packages with Composer Source: https://docs.silverstripe.org/en/6/getting_started/composer Run this command after manually editing your composer.json file to update the installed packages and reflect your changes. ```bash composer update ``` -------------------------------- ### Write a unit test for a PHP method Source: https://docs.silverstripe.org/en/6/developer_guides/testing/unit_testing This example demonstrates a basic unit test for the `myMethod` defined in `Page.php`. It uses `assertEquals` to verify the method's output. Test files should reside in the `app/tests` directory and follow naming conventions. ```php // app/tests/PageTest.php namespace App\Test; use Page; use SilverStripe\Dev\SapphireTest; class PageTest extends SapphireTest { public function testMyMethod() { $this->assertEquals(2, Page::myMethod()); } } ``` -------------------------------- ### Example Country Record Source: https://docs.silverstripe.org/en/6/optional_features/graphql/working_with_generic_types/creating_a_generic_type Provides an example of a data record for the 'Country' type, demonstrating the expected structure with 'code' and 'name' values. ```php [ 'code' => 'bt', 'name' => 'Bhutan', ] ``` -------------------------------- ### Controller Redirect Examples Source: https://docs.silverstripe.org/en/6/developer_guides/controllers/redirection Demonstrates different ways to redirect users within a controller. Use `redirect()` for specific URLs or `redirectBack()` to return to the previous page. ```php namespace App\Control; use SilverStripe\Control\Controller; use SilverStripe\Control\HTTPResponse; class MyController extends Controller { // ... public function someMethod(): HTTPResponse { // redirect to Page::goherenow(), i.e.on the contact-us page this will redirect to /contact-us/goherenow/ return $this->redirect($this->Link('goherenow')); // redirect to the URL on www.example.com/goherenow/ assuming your website is hosted at www.example.com // (note the leading slash) return $this->redirect('/goherenow'); // redirect to https://example.com (assuming that is an external website URL) return $this->redirect('https://example.com'); // go back to the previous page return $this->redirectBack(); } } ``` -------------------------------- ### Loading Local File into DBFile Source: https://docs.silverstripe.org/en/6/developer_guides/files/file_storage Demonstrates how to set a DBFile field from a local filesystem path, specifying a destination filename within the assets folder. ```php use App\Model\Banner; // Image could be assigned in other parts of the code using the below $banner = Banner::create(); $banner->Image->setFromLocalFile($tempfile['path'], 'my-folder/my-file.jpg'); ``` -------------------------------- ### Install Queued Jobs Module Source: https://docs.silverstripe.org/en/6/optional_features/queuedjobs Install the Queued Jobs module using Composer. This command adds the necessary package to your Silverstripe project. ```bash composer require symbiote/silverstripe-queuedjobs ``` -------------------------------- ### Create a Dummy Queued Job Source: https://docs.silverstripe.org/en/6/optional_features/queuedjobs/overview Run this command to create a dummy task for testing if the cron job setup is working correctly. ```bash vendor/bin/sake dev/tasks/CreateQueuedJobTask ``` -------------------------------- ### Install Advanced Workflow Module Source: https://docs.silverstripe.org/en/6/optional_features/advancedworkflow Use Composer to install the Advanced Workflow module. This command should be run in your project's root directory. ```bash composer require symbiote/silverstripe-advancedworkflow ``` -------------------------------- ### Install MIME Type Validator Module Source: https://docs.silverstripe.org/en/6/developer_guides/files/allowed_file_types Install the silverstripe/mimevalidator module using Composer to enable MIME type validation for file uploads. ```bash composer require silverstripe/mimevalidator ``` -------------------------------- ### Install yarn globally Source: https://docs.silverstripe.org/en/6/contributing/build_tooling Installs the yarn package manager globally using npm, which comes with Node.js. This is a prerequisite for managing JavaScript dependencies. ```bash npm install -g yarn ``` -------------------------------- ### Registering and Retrieving Services with Injector API Source: https://docs.silverstripe.org/en/6/developer_guides/extending/injector Demonstrates imperative registration of a service singleton and retrieving it. This approach is common in testing scenarios. ```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 ```