======================== CODE SNIPPETS ======================== TITLE: Run Craft CMS Setup Wizard (CLI) DESCRIPTION: Initiates the Craft CMS setup process directly from the terminal. This command guides you through database connection and admin account creation. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/installation.md#_snippet_3 LANGUAGE: bash CODE: ``` php craft setup ``` ---------------------------------------- TITLE: Install Nitro via Script DESCRIPTION: Downloads and executes the Nitro installation script from the official installer URL. This is the recommended method for quick setup. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_6 LANGUAGE: bash CODE: ``` bash <(curl -sLS http://installer.getnitro.sh) ``` ---------------------------------------- TITLE: Start DDEV Environment DESCRIPTION: Starts the DDEV containers for the project, bringing the development environment online. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_4 LANGUAGE: bash CODE: ``` ddev start ``` ---------------------------------------- TITLE: Install Commerce Example Templates DESCRIPTION: Copies the example templates from the Commerce distribution to your project's `templates/` directory. This provides a starting point for building your store's frontend. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/5.x/development/example-templates.md#_snippet_0 LANGUAGE: bash CODE: ``` cp -r vendor/craftcms/commerce/example-templates/dist/* ./templates ``` ---------------------------------------- TITLE: Access Craft CMS Setup Wizard (Web) DESCRIPTION: Provides the URL to access the Craft CMS setup wizard through a web browser. This is an alternative to the command-line setup. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/installation.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` URL: https:///index.php?p=admin/install Description: Access the Craft CMS setup wizard via a web browser. Replace '' with your local development server's hostname. Steps: 1. Navigate to the URL in your web browser. 2. Accept the license agreement. 3. Enter database connection details. 4. Create an administrator account. 5. Define system name, base URL, and language. 6. Click 'Finish up' to complete the installation. ``` ---------------------------------------- TITLE: Local Development Setup (npm) DESCRIPTION: Installs project dependencies and starts the local development server for Craft CMS documentation. Ensure Node.js and npm are installed. Restart the process if configuration files are changed. SOURCE: https://github.com/craftcms/docs/blob/main/README.md#_snippet_0 LANGUAGE: bash CODE: ``` npm install npm run docs:dev ``` ---------------------------------------- TITLE: Manual Nitro Installation Steps DESCRIPTION: Provides steps for manually installing Nitro by downloading binaries from GitHub releases. This method involves extracting the archive, making the binary executable, and moving it to the system's PATH. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_3 LANGUAGE: sh CODE: ``` chmod +x ./nitro sudo mv ./nitro /usr/local/bin ``` LANGUAGE: sh CODE: ``` sudo mkdir -p -m 775 /usr/local/bin && sudo chown $USER: /usr/local/bin ``` LANGUAGE: sh CODE: ``` xattr -dr com.apple.quarantine /usr/local/bin/nitro ``` ---------------------------------------- TITLE: Start DDEV Project Environment DESCRIPTION: Starts the DDEV containers for a project, resuming the development environment. This command brings the project back online, allowing you to continue where you left off. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/install.md#_snippet_6 LANGUAGE: bash CODE: ``` ddev start ``` ---------------------------------------- TITLE: Initialize Nitro Environment DESCRIPTION: Runs the Nitro initialization command after the binary has been placed in the PATH. This command guides the user through setting up the Nitro environment. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_10 LANGUAGE: shell CODE: ``` nitro init ``` ---------------------------------------- TITLE: Craft CMS Testing Console Command Setup DESCRIPTION: Utilize the `tests/setup` console command for a quick setup of your Craft CMS testing environment. This command copies example test suite files from Craft's internal structure to your project, simplifying the initial configuration process. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/testing/testing-craft/testing-tips.md#_snippet_3 LANGUAGE: bash CODE: ``` # Install Codeception if not already present composer require codeception/codeception # Run the Craft CMS setup command php craft tests/setup # Build Codeception's test suite codecept build # Ensure you have a .env file configured for your test environment ``` ---------------------------------------- TITLE: Craft CMS New Site Setup Steps DESCRIPTION: Provides a step-by-step guide for adding a new site to a Craft CMS installation, covering essential configuration parameters within the control panel. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/system/sites.md#_snippet_5 LANGUAGE: APIDOC CODE: ``` Setting Up a New Site in Craft CMS: 1. Navigate to Settings -> Sites and click 'New Site'. 2. Assign the site to a Site Group (controls content translation). 3. Provide a Site Name (used in control panel and accessible via `{{ siteName }}` in templates). 4. Craft generates a Site Handle (used for referencing in templates, e.g., `craft.app.sites.getSiteByHandle('beta')`). 5. Select the Site Language. 6. Optionally, toggle 'Is Primary Site?' to set it as the default site. 7. If the site has a unique URL, check 'This site has its own base URL' and enter the Base URL. 8. Save the new site. ``` ---------------------------------------- TITLE: Create Craft Project with Composer DESCRIPTION: Installs a new Craft CMS project using Composer. Ensure you have Composer 1.3.0 or later installed. Replace 'path/to/my-project' with your desired project directory. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/installation.md#_snippet_0 LANGUAGE: bash CODE: ``` composer create-project "craftcms/craft:^3" path/to/my-project ``` ---------------------------------------- TITLE: Start DDEV Project DESCRIPTION: Initiates the DDEV development environment for a Craft CMS project. This command typically starts all necessary services (like web server, database) defined in the project's DDEV configuration. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/install.md#_snippet_8 LANGUAGE: bash CODE: ``` ddev start ``` ---------------------------------------- TITLE: Launch DDEV Project DESCRIPTION: Launches the DDEV environment for the current project, making it accessible via a browser. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_3 LANGUAGE: bash CODE: ``` ddev launch ``` ---------------------------------------- TITLE: Craft CMS Console Setup Command DESCRIPTION: Command-line instruction for setting up a Craft CMS testing environment. This command copies example test suite files to a specified directory. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/testing/testing-craft/testing-tips.md#_snippet_4 LANGUAGE: shell CODE: ``` # Run the setup command php craft tests/setup # Or specify a target directory # php craft tests/setup /path/to/your/test/suite # After setup, install Codeception and build: composer require codeception/codeception codecept build # Ensure a .env file is present. ``` ---------------------------------------- TITLE: `nitro add` Command for Site Setup DESCRIPTION: Demonstrates the `nitro add` command to set up a site for an existing project. It guides the user through specifying the hostname, web root, and PHP version, and applies changes including host file modifications. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/usage.md#_snippet_0 LANGUAGE: bash CODE: ``` $ cd /path/to/project $ nitro add Adding site… Enter the hostname [mysite.test]: ✓ setting hostname to mysite.test ✓ adding site ~/dev/support/mysite.test Enter the web root for the site [web]: ✓ using web root web Choose a PHP version: 1. 8.0 2. 7.4 3. 7.3 4. 7.2 5. 7.1 6. 7.0 Enter your selection: 2 ✓ setting PHP version 7.4 … saving file ✓ Site added 🌍 Apply changes now [Y/n]? y Checking network… ✓ network ready Checking proxy… ✓ proxy ready Checking databases… … checking mysql-8.0-3306.nitro ✓ … checking postgres-13-5432.nitro ✓ Checking mounts… … checking ~/dev/craftcms/cms-3 ✓ Checking services… … checking mailhog service ✓ Checking sites… … checking mysite.test ✓ Checking proxy… … updating proxy ✓ Modifying hosts file (you might be prompted for your password) Adding sites to hosts file… … modifying hosts file ✓ Nitro is up and running 😃 ``` ---------------------------------------- TITLE: Nitro Commands Reference DESCRIPTION: Provides details on essential Nitro commands for managing the development environment. Includes commands for listing services and destroying resources. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_15 LANGUAGE: APIDOC CODE: ``` Nitro Commands: ls Lists all running Nitro services and their configurations. Example: nitro ls destroy Removes all Docker networks, containers, and volumes created by Nitro. This is a critical step for uninstallation. Example: nitro destroy init Initializes the Nitro environment, often prompting for configuration details. Example: nitro init Troubleshooting Commands: nitro ls Used to verify the status of the 'nitro-proxy' container. Customization: Customize Nitro's default ports if conflicts arise with other services. See: customizing.md#how-to-customize-nitro-s-defaults ``` ---------------------------------------- TITLE: Launch Craft CMS Project DESCRIPTION: Launches the locally developed Craft CMS project in the browser. This command starts the DDEV environment and opens the project's welcome screen. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/install.md#_snippet_3 LANGUAGE: bash CODE: ``` ddev launch ``` ---------------------------------------- TITLE: Create and Navigate Project Directory DESCRIPTION: Creates a new directory for your Craft CMS project and changes the current directory into it. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_0 LANGUAGE: bash CODE: ``` mkdir my-craft-project cd my-craft-project/ ``` ---------------------------------------- TITLE: Install Nitro via Bash Script DESCRIPTION: Installs Nitro by downloading and executing an installer script using curl and bash. This method is suitable for both macOS and Linux users who prefer a direct script-based installation. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_0 LANGUAGE: sh CODE: ``` bash <(curl -sLS http://installer.getnitro.sh) ``` ---------------------------------------- TITLE: Scaffold Craft CMS Project with Composer DESCRIPTION: Uses Composer to create a new Craft CMS project from the official starter project, specifying the desired version. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_2 LANGUAGE: bash CODE: ``` ddev composer create-project "craftcms/craft:^4" ``` ---------------------------------------- TITLE: Import Database Backup DESCRIPTION: Imports a SQL database backup into the DDEV environment for the current project. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_6 LANGUAGE: bash CODE: ``` ddev import-db path/to/backup.sql ``` ---------------------------------------- TITLE: Composer Installation Log Indicator DESCRIPTION: Composer's installation log should indicate that the package was installed via a symlink when using a path repository. This confirms the local development setup. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/extend/plugin-guide.md#_snippet_6 LANGUAGE: bash CODE: ``` - Installing package/name (X.Y.Z): Symlinking from ../my-plugin ``` ---------------------------------------- TITLE: Craft CMS Project Directory Structure DESCRIPTION: Illustrates the typical directory layout of a Craft CMS project after installation. This structure helps organize project files, configurations, and assets. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/installation.md#_snippet_1 LANGUAGE: treeview CODE: ``` my-project/ ├── config/ │ └── ... ├── modules/ │ └── ... ├── storage/ │ └── ... ├── templates/ │ └── ... ├── vendor/ │ └── ... ├── web/ │ └── ... ├── .env ├── .env.example ├── .gitignore ├── composer.json ├── composer.lock └── craft ``` ---------------------------------------- TITLE: Install Docker using Homebrew (macOS) DESCRIPTION: Installs Docker Desktop on macOS using the Homebrew package manager. This is a prerequisite step for installing and running Nitro on macOS. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_2 LANGUAGE: sh CODE: ``` brew install homebrew/cask/docker ``` ---------------------------------------- TITLE: Create /usr/local/bin Directory DESCRIPTION: Creates the /usr/local/bin directory if it doesn't exist and sets appropriate permissions (775) and ownership to the current user. This is a step in manual installation to place the Nitro binary in the system's PATH. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_8 LANGUAGE: shell CODE: ``` sudo mkdir -p -m 775 /usr/local/bin && sudo chown $USER: /usr/local/bin ``` ---------------------------------------- TITLE: Scaffold Craft CMS Project DESCRIPTION: Scaffolds a new Craft CMS project using Composer from the official starter project. This command downloads the necessary files and initiates the project setup wizard. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/install.md#_snippet_2 LANGUAGE: bash CODE: ``` ddev composer create-project "craftcms/craft" ``` ---------------------------------------- TITLE: Copy Example Templates to Project DESCRIPTION: Copies the entire set of Commerce example templates from the distribution directory into your project's main templates folder. This is a straightforward way to integrate the pre-built templates. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/3.x/example-templates.md#_snippet_0 LANGUAGE: bash CODE: ``` cp -r vendor/craftcms/commerce/example-templates/dist/* ./templates ``` ---------------------------------------- TITLE: Make Nitro Executable DESCRIPTION: Grants execute permissions to the Nitro binary file. This is part of the manual installation process to ensure the command can be run. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_7 LANGUAGE: shell CODE: ``` chmod +x ./nitro ``` ---------------------------------------- TITLE: Travis CI: Setup Databases and Extensions DESCRIPTION: Prepares the testing environment by displaying version information, creating necessary databases (MySQL and PostgreSQL), configuring SQL modes, and installing extensions like Imagick. It also sets up environment configuration files. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/testing/ci.md#_snippet_3 LANGUAGE: yaml CODE: ``` before_script: - | # show some version and environment information php --version composer --version php -r "echo INTL_ICU_VERSION . "\n";" php -r "echo INTL_ICU_DATA_VERSION . "\n";" psql --version mysql --version - travis_retry mysql -e 'CREATE DATABASE `craft-test`;'; - mysql -e "SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"; - psql -U postgres -c 'CREATE DATABASE "craft-test";'; - pear config-set preferred_state beta - pecl channel-update pecl.php.net - yes | pecl install imagick - cp tests/.env.example.$DB tests/.env ``` LANGUAGE: yaml CODE: ``` - cp tests/.env.example.$DB tests/.env ``` ---------------------------------------- TITLE: Travis CI Before Script Setup DESCRIPTION: Prepares the environment before running tests. This includes displaying version information, creating databases (MySQL and PostgreSQL), setting SQL modes, installing Imagick, and copying environment configuration files. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/testing/ci.md#_snippet_3 LANGUAGE: bash CODE: ``` before_script: - | # show some version and environment information php --version composer --version php -r "echo INTL_ICU_VERSION . "\n";" php -r "echo INTL_ICU_DATA_VERSION . "\n";" psql --version mysql --version - travis_retry mysql -e 'CREATE DATABASE `craft-test`;'; - mysql -e "SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';"; - psql -U postgres -c 'CREATE DATABASE "craft-test";'; - pear config-set preferred_state beta - pecl channel-update pecl.php.net - yes | pecl install imagick - cp tests/.env.example.$DB tests/.env ``` ---------------------------------------- TITLE: Environment Variable Setup DESCRIPTION: Demonstrates how to copy an example environment file to create the active configuration file, typically used for sensitive or environment-specific settings. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/system/directory-structure.md#_snippet_2 LANGUAGE: bash CODE: ``` cp .env.example .env ``` ---------------------------------------- TITLE: General Config File Example (PHP) DESCRIPTION: Provides an example of a primary general configuration file using a key-value map. This file is evaluated for all application types. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/configure.md#_snippet_10 LANGUAGE: php CODE: ``` return [ 'aliases' => [ '@webroot' => dirname(__DIR__) . '/web', ], ]; ``` ---------------------------------------- TITLE: Static Method Naming DESCRIPTION: Static methods should generally not start with 'get' to distinguish them from instance getter methods. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/extend/coding-guidelines.md#_snippet_3 LANGUAGE: php CODE: ``` className() displayName() ``` ---------------------------------------- TITLE: Craft Console Controller Example DESCRIPTION: Provides an example of a `GreetController` extending `craft\console\Controller`. It defines a default action, handles options like `--who`, and outputs greetings using `stdout`. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/extend/commands.md#_snippet_2 LANGUAGE: php CODE: ``` namespace modules\console\controllers; use craft\console\Controller; use craft\helpers\Console; use yii\console\ExitCode; /** * Greet Controller */ class GreetController extends Controller { public $defaultAction = 'developer'; /** * @var string|null The name used when referring to the runner. */ public ?string $who = null; public function options($actionID): array { $options = parent::options($actionID); // Always allow a --who flag: $options[] = 'who'; switch ($actionID) { case 'developer': // Action-specific arguments: // $options[] = '...'; break; } return $options; } /** * Issues a greeting to new Craft developers. */ public function actionDeveloper(): int { $who = $this->who ?? 'world'; $this->stdout("Hello, {$who}!", Console::FG_GREEN); return ExitCode::OK; } } ``` ---------------------------------------- TITLE: Symlink Example Templates DESCRIPTION: Symlink specific example template folders (e.g., 'shop') into your project's templates directory. This is recommended for active development to ensure you always have up-to-date examples, especially when testing gateway plugins with unreleased Commerce versions. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/4.x/example-templates.md#_snippet_1 LANGUAGE: bash CODE: ``` ln -s vendor/craftcms/commerce/example-templates/dist/shop ./templates/shop ``` ---------------------------------------- TITLE: Symlink Example Templates for Development DESCRIPTION: Creates a symbolic link for the 'shop' directory of the Commerce example templates. This allows for live development updates by linking the vendor directory to your project's templates folder. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/3.x/example-templates.md#_snippet_1 LANGUAGE: bash CODE: ``` ln -s vendor/craftcms/commerce/example-templates/dist/shop ./templates/shop ``` ---------------------------------------- TITLE: Plugin Install Migration Template (PHP) DESCRIPTION: Defines the structure for a plugin's special 'Install' migration, which handles the initial setup and teardown of plugin-specific database schema. It should extend Craft's `Migration` class and implement `safeUp()` and `safeDown()` methods. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/extend/migrations.md#_snippet_9 LANGUAGE: php CODE: ``` ``` ---------------------------------------- TITLE: Configure DDEV for Craft CMS Project DESCRIPTION: Configures DDEV for a Craft CMS project, specifying the project type and the web server's document root. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_1 LANGUAGE: bash CODE: ``` ddev config --project-type=craftcms --docroot=web ``` ---------------------------------------- TITLE: Craft CMS Element Getters and Property Access DESCRIPTION: Explains the 'getter' convention where methods starting with 'get' and accepting no arguments can be accessed like properties. For example, `entry.getLink()` can be used as `entry.link` in templates. This pattern is a feature of Craft's underlying Yii framework. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/system/elements.md#_snippet_15 LANGUAGE: APIDOC CODE: ``` ::: tip Any method beginning with `get` (and that accepts no arguments) can be used like a [property](#properties) by removing the prefix and down-casing the first letter. For example, `{{ entry.getLink() }}` can also be used as `{{ entry.link }}` in a template. This is referred to as a “getter” or “magic getter,” and works in part due to the [design of Yii](guide:concept-properties), Craft’s underlying PHP library. ::: `getLink()` - Build an HTML anchor tag with its front-end URL and title. _Elements with URLs only._ `getUrl()` - Builds a complete front-end URL based on the element’s URI. ``` ---------------------------------------- TITLE: Launch DDEV Project DESCRIPTION: Opens the DDEV-managed Craft CMS project in your default web browser, allowing you to view the installed site. SOURCE: https://github.com/craftcms/docs/blob/main/docs/getting-started-tutorial/install/README.md#_snippet_3 LANGUAGE: sh CODE: ``` ddev launch ``` ---------------------------------------- TITLE: Getter Method Naming DESCRIPTION: Guidelines for naming getter methods in PHP. Methods that return a value without arguments should start with 'get' and have a corresponding @property tag. Methods with arguments should start with 'get' if it sounds natural. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/extend/coding-guidelines.md#_snippet_2 LANGUAGE: php CODE: ``` getAuthor() getIsSystemOn() getHasFreshContent() ``` LANGUAGE: php CODE: ``` getError($attribute) hasErrors($attribute = null) ``` ---------------------------------------- TITLE: Install Nitro using Homebrew (macOS) DESCRIPTION: Installs Nitro on macOS using the Homebrew package manager. This method requires Homebrew and Docker to be pre-installed and simplifies the Nitro installation process. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_1 LANGUAGE: sh CODE: ``` brew install craftcms/nitro/nitro ``` ---------------------------------------- TITLE: Move Nitro Binary to PATH DESCRIPTION: Moves the compiled Nitro binary to the /usr/local/bin directory, making it accessible from any terminal location. Requires superuser privileges. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_9 LANGUAGE: shell CODE: ``` sudo mv ./nitro /usr/local/bin ``` ---------------------------------------- TITLE: Install Nitro on macOS and Linux DESCRIPTION: Installs Nitro using a shell script. Requires Multipass to be installed beforehand. The script downloads and executes the Nitro installer, then prompts the user for machine configuration. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/1.x/installation.md#_snippet_0 LANGUAGE: bash CODE: ``` bash <(curl -sLS https://raw.githubusercontent.com/craftcms/nitro/v1/install.sh) ``` ---------------------------------------- TITLE: Create and Navigate Project Directory DESCRIPTION: Creates a new directory for your Craft project and changes the current directory into it. This is the first step in setting up a local development environment. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/install.md#_snippet_0 LANGUAGE: bash CODE: ``` mkdir my-craft-project cd my-craft-project/ ``` ---------------------------------------- TITLE: Nitro Site Configuration Example DESCRIPTION: Example configuration for a Nitro site, specifying the host machine path and webroot. This determines how your local project directory is mapped into the Nitro container. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/how-nitro-works.md#_snippet_0 LANGUAGE: yaml CODE: ``` path: ~\/dev webroot: my-project\/web ``` ---------------------------------------- TITLE: Run Composer Install with Nitro DESCRIPTION: Utilize Nitro's `composer` command to execute Composer operations, such as installing dependencies, without requiring Composer to be installed on your host machine. This example shows the command and its typical output. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/composer.md#_snippet_0 LANGUAGE: bash CODE: ``` $ cd ~/dev/my-craft-project $ nitro composer install … checking /Users/oli/dev/my-craft-project/composer.json ✓ Installing dependencies from lock file (including require-dev) Verifying lock file contents can be installed on current platform. Nothing to install, update or remove Generating optimized autoload files 79 packages you are using are looking for funding. Use the `composer fund` command to find out more! composer install completed 🤘 ``` ---------------------------------------- TITLE: `nitro create` Command for New Project & Site DESCRIPTION: Illustrates the `nitro create` command for initializing a new project and site, defaulting to a Craft CMS setup. It covers downloading the project, setting hostname, PHP version, database creation, and environment file updates. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/usage.md#_snippet_1 LANGUAGE: bash CODE: ``` $ nitro create tutorial Downloading https://github.com/craftcms/craft/archive/HEAD.zip ... … setting up project ✓ New site downloaded 🤓 Enter the hostname [tutorial.nitro]: ✓ setting hostname to tutorial.nitro ✓ adding site ~/dev/tutorial Enter the web root for the site [web]: ✓ using web root web Choose a PHP version: 1. 8.0 2. 7.4 3. 7.3 4. 7.2 5. 7.1 6. 7.0 Enter your selection: 1 ✓ setting PHP version 8.0 Add a database for the site [Y/n] Select the database engine: 1. mysql-8.0-3306.database.nitro 2. postgres-13-5432.database.nitro Enter your selection: 2 Enter the new database name: tutorial … creating database tutorial ✓ Database added 💪 Should we update the env file? [Y/n] y .env updated! … checking /Users/oli/dev/tutorial/composer.json ✓ No lock file found. Updating dependencies instead of installing from lock file. Use composer update over composer install if you do not have a lock file. Loading composer repositories with package information Updating dependencies Lock file operations: 87 installs, 0 updates, 0 removals # removed for brevity ``` LANGUAGE: bash CODE: ``` nitro create https://github.com/craftcms/demo my-project ``` ---------------------------------------- TITLE: Symlink Commerce Example Templates DESCRIPTION: Creates a symbolic link for the example templates directory into your project's `templates/` folder. This is recommended for active development to ensure templates are always up-to-date. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/5.x/development/example-templates.md#_snippet_1 LANGUAGE: bash CODE: ``` ln -s vendor/craftcms/commerce/example-templates/dist/shop ./templates/shop ``` ---------------------------------------- TITLE: Scaffold Craft CMS Project with Composer DESCRIPTION: Uses Composer via DDEV to create a new Craft CMS project from the official starter template. This command initiates an interactive setup wizard. SOURCE: https://github.com/craftcms/docs/blob/main/docs/getting-started-tutorial/install/README.md#_snippet_2 LANGUAGE: sh CODE: ``` ddev composer create -y "craftcms/craft" ``` ---------------------------------------- TITLE: Uninstall Nitro via Homebrew (macOS) DESCRIPTION: Removes Nitro if it was originally installed using the Homebrew package manager on macOS. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_14 LANGUAGE: shell CODE: ``` brew uninstall nitro ``` ---------------------------------------- TITLE: Plugin Lifecycle: onAfterInstall DESCRIPTION: This method is called immediately after the plugin's row is saved to the `plugins` database table and its associated tables have been created based on its records. It's a hook for post-installation setup. SOURCE: https://github.com/craftcms/docs/blob/main/docs/2.x/plugins/setting-things-up.md#_snippet_5 LANGUAGE: php CODE: ``` public function onAfterInstall() { // Plugin installation logic here } ``` ---------------------------------------- TITLE: Composer JSON Scripts for Craft CMS DESCRIPTION: Example of a `composer.json` file demonstrating how to configure post-install commands. This script automatically runs `craft install/check` and `craft up` after Composer installs or updates packages, ensuring the Craft environment is synchronized. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/update.md#_snippet_6 LANGUAGE: json CODE: ``` { "require": { "craftcms/cms": "^5.0.0", "vlucas/phpdotenv": "^5.4.0" // ... }, // ... "scripts": { "post-install-cmd": "@php craft install/check && php craft up --interactive=0 || exit 0" } } ``` ---------------------------------------- TITLE: Copy Example Templates DESCRIPTION: Copies the example templates that Commerce ships with into your project’s template folder. It prompts for a folder name and can overwrite existing ones with the `--overwrite` flag. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/5.x/reference/console-commands.md#_snippet_0 LANGUAGE: php CODE: ``` $ php craft commerce/example-templates A folder will be copied to your templates directory. Choose folder name: [shop] myshop Copying ... Done! ``` ---------------------------------------- TITLE: Install Craft Commerce with DDEV DESCRIPTION: Installs Craft Commerce using Composer and the Craft CLI within a DDEV environment. These commands ensure the installation process runs inside the correct Docker container managed by DDEV. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/4.x/installation.md#_snippet_1 LANGUAGE: bash CODE: ``` ddev composer require -w craftcms/commerce ddev craft plugin/install commerce ``` ---------------------------------------- TITLE: Start Nitro Containers DESCRIPTION: Starts all Nitro containers. Optionally, it can start containers for a specific site hostname, targeting only that site's containers instead of all. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/commands.md#_snippet_40 LANGUAGE: shell CODE: ``` nitro start ``` LANGUAGE: shell CODE: ``` $ nitro start Starting Nitro… ✓ mysite.test ready ✓ mailhog.service.nitro ready ✓ postgres-13-5432.nitro ready ✓ mysql-8.0-3306.nitro ready ✓ nitro-proxy ready Nitro started 👍 ``` ---------------------------------------- TITLE: Install Generator via Composer DESCRIPTION: Installs the Generator package as a development dependency using Composer. This command is necessary for projects started before Craft CMS version 4.3.5. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/extend/generator.md#_snippet_0 LANGUAGE: bash CODE: ``` composer require craftcms/generator --dev ``` ---------------------------------------- TITLE: Set WSL Default Version to 2 DESCRIPTION: Configures the Windows Subsystem for Linux (WSL) to use version 2 as the default for all new distributions. This is a prerequisite for Nitro installation on Windows. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_4 LANGUAGE: bash CODE: ``` wsl --set-default-version 2 ``` ---------------------------------------- TITLE: Copy Example Templates DESCRIPTION: Customizes and copies example templates into your project’s template folder. This command prompts the user for input regarding the folder name, CDN usage for resources, and base Tailwind CSS color. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/3.x/console-commands.md#_snippet_0 LANGUAGE: shell CODE: ``` $ php craft commerce/example-templates A folder will be copied to your templates directory. Choose folder name: [shop] myshop Use CDN link to resources (tailwind)? (yes|no) [yes]: yes Base Tailwind CSS color: [gray,red,yellow,green,blue,indigo,purple,pink,?]: green Attempting to copy example templates ... Copying ... Done! ``` ---------------------------------------- TITLE: Install Craft Commerce via Composer DESCRIPTION: Installs the Craft Commerce plugin using Composer and then installs it within the Craft CMS application. This is the standard method for adding Commerce to an existing Craft 4 project. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/4.x/installation.md#_snippet_0 LANGUAGE: bash CODE: ``` composer require -w craftcms/commerce php craft plugin/install commerce ``` ---------------------------------------- TITLE: Install Nitro on Windows DESCRIPTION: Manually installs Nitro on Windows 10 Pro with Hyper-V. Requires downloading a zip file, extracting it, and adding the Nitro executable to the system's PATH. Initialization is done via the command line. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/1.x/installation.md#_snippet_1 LANGUAGE: bash CODE: ``` setx path "%PATH%;%USERPROFILE%\Nitro" nitro init ``` ---------------------------------------- TITLE: Get Previous and Next Category Example DESCRIPTION: Shows how to retrieve the previous and next sibling categories based on specified parameters like section and order. This example uses the getPrev() and getNext() methods. SOURCE: https://github.com/craftcms/docs/blob/main/docs/2.x/templating/categorymodel.md#_snippet_4 LANGUAGE: twig CODE: ``` {% set params = { section: 'cocktails', order: 'title' } %} {% set prevWhiskey = category.getPrev(params) %} {% set nextWhiskey = category.getNext(params) %} {% if prevWhiskey %}

Previous: {{ prevWhiskey.title }}

{% endif %} {% if nextWhiskey %}

Next: {{ nexWhiskey.title }}

{% endif %} ``` ---------------------------------------- TITLE: PHP Configuration Example DESCRIPTION: Example of how to configure Craft Commerce settings in `commerce.php`. This snippet demonstrates defining global settings and environment-specific overrides for configuration values like `purgeInactiveCartsDuration`. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/2.x/configuration.md#_snippet_0 LANGUAGE: php CODE: ``` return [ // Global settings '*' => [ // ... ], // Dev environment settings 'dev' => [ 'purgeInactiveCartsDuration' => P1D, // ... ], // Staging environment settings 'staging' => [ // ... ], // Production environment settings 'production' => [ // ... ], ]; ``` ---------------------------------------- TITLE: Install Craft Commerce via Composer DESCRIPTION: Installs the Craft Commerce plugin into an existing Craft 4 project using Composer and then installs the plugin via the Craft console. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/5.x/install.md#_snippet_0 LANGUAGE: bash CODE: ``` composer require -w craftcms/commerce php craft plugin/install commerce ``` ---------------------------------------- TITLE: Defer Plugin Setup with `onInit()` Callback DESCRIPTION: Register a callback function using `Craft::$app->onInit()` to defer plugin setup tasks until Craft is fully initialized. This prevents race conditions when creating element queries or loading the Twig environment prematurely. The callback executes immediately if Craft is already initialized. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/extend/plugin-guide.md#_snippet_5 LANGUAGE: php CODE: ``` namespace mynamespace; use Craft; class Plugin extends \craft\base\Plugin { public function init(): void { // Always let the parent init() method run, first: parent::init(); // Set up critical components + features... // Defer some setup tasks until Craft is fully initialized: Craft::$app->onInit(function() { // ... }); } // ... } ``` ---------------------------------------- TITLE: Create Product Query DESCRIPTION: Provides examples of initiating a product query in different languages. This is the first step to fetching products based on specific criteria. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/5.x/system/products-variants.md#_snippet_5 LANGUAGE: twig CODE: ``` {# Create a new product query #} {% set myProductQuery = craft.products() ``` LANGUAGE: php CODE: ``` // Create a new product query $myProductQuery = \craft\commerce\elements\Product::find(); ``` LANGUAGE: graphql CODE: ``` # Create a new product query { products { # ... } } ``` ---------------------------------------- TITLE: Stop DDEV Environment DESCRIPTION: Stops the DDEV containers for the project, freeing up system resources. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/installation.md#_snippet_5 LANGUAGE: bash CODE: ``` ddev stop ``` ---------------------------------------- TITLE: Writing a File with Craft CMS FileHelper DESCRIPTION: Demonstrates writing content to a file using Craft CMS's `FileHelper::writeToFile` method. It shows how to obtain a temporary directory path and construct a unique filename for the file. The example highlights using Craft's path services for temporary file storage, which aids in automatic cleanup. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/extend/topics.md#_snippet_3 LANGUAGE: php CODE: ``` use Craft; use craft\helpers\FileHelper; $content = '# Todo List'; $filename = 'todos.md'; $tempDir = Craft::$app->getPath()->getTempPath(); $path = $tempDir . DIRECTORY_SEPARATOR . uniqid() . $filename; FileHelper::writeToFile($path, $content); ``` ---------------------------------------- TITLE: Nitro CLI Example Usage DESCRIPTION: An example demonstrating the usage of the `nitro keys` command and subsequent interaction. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/1.x/commands.md#_snippet_18 LANGUAGE: shell CODE: ``` $ nitro keys 1 - id_rsa 2 - personal_rsa Select the key to add to "nitro-dev"? [1] Transferred the key "id_rsa" into "nitro-dev". ``` ---------------------------------------- TITLE: Add Site with `nitro add` Command DESCRIPTION: Demonstrates how to add a new site to Nitro using the `nitro add` command. This process involves specifying the hostname and web root, applying configuration changes, mounting project files, and updating the system's hosts file. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/1.x/usage.md#_snippet_0 LANGUAGE: bash CODE: ``` $ cd /path/to/project $ nitro add Enter the hostname [plugins-dev] example.test Enter the web root [web] Added plugins-dev to config file. Apply changes from config? [yes] Mounting /path/to/project to nitro-dev Adding site example.test to nitro-dev Applied changes from /Users/oli/.nitro/nitro-dev.yaml Editing your hosts file Password: ****** ``` ---------------------------------------- TITLE: Example Receipt Template DESCRIPTION: A link to an example Twig template for generating order PDFs. This serves as a starting point for creating custom PDF designs, emphasizing the need to avoid extending site layouts and to test with actual rendered PDFs. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/4.x/pdfs.md#_snippet_2 LANGUAGE: twig CODE: ``` https://github.com/craftcms/commerce/blob/4.x/example-templates/dist/shop/_private/receipt/index.twig ``` ---------------------------------------- TITLE: Install Craft Commerce via Composer DESCRIPTION: This command installs the specified version of Craft Commerce (^2.0) into your Craft 3 project using Composer. Ensure Composer is installed and you are in your project's root directory. SOURCE: https://github.com/craftcms/docs/blob/main/docs/commerce/2.x/installation.md#_snippet_0 LANGUAGE: bash CODE: ``` composer require craftcms/commerce:"^2.0" ``` ---------------------------------------- TITLE: Reference Tag Examples DESCRIPTION: Provides practical examples of reference tags, demonstrating how to access specific properties of different element types and how to specify sites. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/reference-tags.md#_snippet_3 LANGUAGE: twig CODE: ``` # Returns the filename of an asset with ID 123 {asset:123:filename} # Returns the URL of an entry in the 'blog' section with slug 'whats-on-tap' {entry:blog/whats-on-tap} # Returns the 'intro' field value for an entry in the 'blog' section ('whats-on-tap') from the 'en' site {entry:blog/whats-on-tap@en:intro} # Returns the price of a Commerce Variant object with ID 123 {craft\commerce\Variant:123:price} # Returns the UID of a global set with handle 'aGlobalSet' {globalset:aGlobalSet:uid} ``` ---------------------------------------- TITLE: Install Plugin via Composer (Bash) DESCRIPTION: Command to install a local plugin into a Craft project using Composer after setting up a path repository. Assumes the plugin's package name is correctly defined in its own composer.json. SOURCE: https://github.com/craftcms/docs/blob/main/docs/3.x/extend/plugin-guide.md#_snippet_4 LANGUAGE: bash CODE: ``` # go to the project directory cd /path/to/my-project # Require your plugin (replace 'package/name' with your plugin's actual name) composer require package/name:* ``` ---------------------------------------- TITLE: Craft CLI: Install Plugin DESCRIPTION: This command installs a plugin into your Craft CMS project using its unique handle. It also automatically runs any database migrations associated with the plugin. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/plugins.md#_snippet_1 LANGUAGE: bash CODE: ``` php craft plugin/install commerce ``` ---------------------------------------- TITLE: Craft CMS Unit Test Example DESCRIPTION: A sample PHP unit test class for Craft CMS using Codeception. It demonstrates setting and asserting the application edition using `Craft::$app->setEdition()` and `Craft::$app->getEdition()`, verifying core application behavior. SOURCE: https://github.com/craftcms/docs/blob/main/docs/4.x/testing/testing-craft/setup.md#_snippet_7 LANGUAGE: php CODE: ``` setEdition(Craft::Pro); $this->assertSame( Craft::Pro, Craft::$app->getEdition() ); } } ``` ---------------------------------------- TITLE: Nitro CLI Commands Reference DESCRIPTION: Provides essential Nitro CLI commands for project management. Includes commands for adding sites, applying configurations, editing settings, and retrieving machine information, crucial for development workflows. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/1.x/usage.md#_snippet_2 LANGUAGE: APIDOC CODE: ``` nitro add - Adds a new site to Nitro. - Prompts for hostname and web root. - Updates configuration and mounts. nitro apply - Applies changes from the Nitro configuration file (`nitro.yaml` or `nitro-dev.yaml`) to the machine. nitro edit - Opens the Nitro configuration file in a text editor. nitro info - Displays information about the Nitro machine, including its IP address, state, and resource usage. nitro ssh - Establishes an SSH connection to the Nitro machine. nitro db add - Adds a new database to the Nitro machine, prompting for engine and name. ``` ---------------------------------------- TITLE: Nitro Software Installation Commands DESCRIPTION: Installs or adds software components like Composer, MySQL, and PostgreSQL to the Nitro virtual machine. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/1.x/commands.md#_snippet_11 LANGUAGE: APIDOC CODE: ``` nitro install composer Installs Composer inside a virtual machine. Options: -m, --machine The name of the machine to use. Defaults to `nitro-dev`. Example: $ nitro install composer Composer is now installed on "nitro-dev". nitro install mysql Adds a new MySQL database engine. Options: -m, --machine The name of the machine to use. Defaults to `nitro-dev`. Example: $ nitro install mysql Enter the MySQL version to install: 5.6 Enter the MySQL port number: 3306 Adding MySQL version "5.6" on port "3306" Apply changes from config now? [yes] nitro install postgres Adds a new PostgreSQL database engine. Options: -m, --machine The name of the machine to use. Defaults to `nitro-dev`. Example: $ nitro install postgres Enter the PostgreSQL version to install: 11 Enter the MySQL port number: 5432 Adding MySQL version "11" on port "5432" Apply changes from config now? [yes] ``` ---------------------------------------- TITLE: Craft CMS Plugin Entry Point: Plugin.php DESCRIPTION: This PHP snippet shows the basic structure for your plugin's main entry point, `src/Plugin.php`. It demonstrates how to extend `craft\base\Plugin` and implement the `init()` method for custom initialization logic, event registration, and setup. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/extend/plugin-guide.md#_snippet_4 LANGUAGE: php CODE: ``` namespace mynamespace; class Plugin extends \craft\base\Plugin { public function init() { parent::init(); // Custom initialization code goes here... } } ``` ---------------------------------------- TITLE: Remove Nitro Command (Linux/macOS) DESCRIPTION: Deletes the Nitro executable file from the /usr/local/bin directory. This command requires superuser privileges. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_12 LANGUAGE: shell CODE: ``` sudo rm /usr/local/bin/nitro ``` ---------------------------------------- TITLE: Craft CMS Ajax Request for Session Info DESCRIPTION: An example of making an Ajax GET request to fetch session and user information from Craft CMS. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/development/forms.md#_snippet_3 LANGUAGE: javascript CODE: ``` // Get info about the current session (guests) and user (if logged in): fetch('/actions/users/session-info', { headers: { 'Accept': 'application/json', }, }) .then(response => response.json()) .then(result => console.log(result)); // -> { isGuest: true, timeout: 0, csrfTokenValue: '...' } ``` ---------------------------------------- TITLE: Composer for Craft CMS DESCRIPTION: Composer is used for managing Craft CMS dependencies and installing the starter project. It's a key tool for setting up a Craft project from scratch or using the starter project. SOURCE: https://github.com/craftcms/docs/blob/main/docs/5.x/install.md#_snippet_10 LANGUAGE: bash CODE: ``` composer create-project craftcms/craft-cms my-project-name ``` ---------------------------------------- TITLE: Plugin Lifecycle: onBeforeInstall DESCRIPTION: This method is called just before the plugin's row is saved to the `plugins` database table and its tables are created. It allows for pre-installation checks or preparations. SOURCE: https://github.com/craftcms/docs/blob/main/docs/2.x/plugins/setting-things-up.md#_snippet_6 LANGUAGE: php CODE: ``` public function onBeforeInstall() { // Pre-installation logic here } ``` ---------------------------------------- TITLE: Destroy Nitro Docker Resources DESCRIPTION: Removes all Docker networks, containers, and volumes associated with Nitro. This is the first step in completely uninstalling Nitro. SOURCE: https://github.com/craftcms/docs/blob/main/docs/nitro/2.x/installation.md#_snippet_11 LANGUAGE: shell CODE: ``` nitro destroy ``` ---------------------------------------- TITLE: Primary Plugin Class Example DESCRIPTION: This PHP code snippet demonstrates the structure of a primary plugin class in Craft CMS. It includes essential methods for defining the plugin's name, version, developer, and developer URL. SOURCE: https://github.com/craftcms/docs/blob/main/docs/2.x/plugins/setting-things-up.md#_snippet_0 LANGUAGE: php CODE: ```