### Install Winter CMS Source: https://wintercms.com/docs/v1.2/docs/console/setup-maintenance The `winter:install` command guides users through the initial setup of Winter CMS. It prompts for database credentials, application URL, encryption key, and administrator details. Configuration can be further adjusted in `config/app.php` and `config/cms.php`. This command should not be run after `winter:env`. ```bash php artisan winter:install ``` -------------------------------- ### Install and Manage Supervisor on Ubuntu Source: https://wintercms.com/docs/v1.2/docs/services/queues This Bash snippet shows how to install Supervisor on Ubuntu using apt-get. It also includes the commands to make Supervisor aware of new configuration files (`reread`), apply those changes (`update`), and start a specific program group (`start`). ```bash sudo apt-get install supervisor ``` ```bash sudo supervisorctl reread ``` ```bash sudo supervisorctl update ``` ```bash sudo supervisorctl start winter-worker:* ``` -------------------------------- ### Basic Mix Asset Compilation Example Source: https://wintercms.com/docs/v1.2/docs/console/asset-compilation-mix This example demonstrates a basic asset compilation using Laravel Mix, specifying JavaScript and PostCSS files. It assumes the standard Mix setup where 'resources/js/app.js' and 'resources/css/app.css' are the input files and 'public/js' and 'public/css' are the output directories. ```javascript mix.js('resources/js/app.js', 'public/js') .postCss('resources/css/app.css', 'public/css'); ``` -------------------------------- ### Markdown Structure Example Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Provides an example of the recommended heading structure for WinterCMS documentation using GitHub Flavored Markdown. It shows the hierarchy of main titles, section headings, and sub-section headings. ```markdown # The main title This is some introductory content for the page itself. ## Section heading The section may have some introductory content here. ### Sub-section heading This is the content of the first sub-section. ### Sub-section 2 heading This is the content of the second sub-section. ## Next section heading ``` -------------------------------- ### Download and Install a Plugin for Winter Source: https://wintercms.com/docs/v1.2/docs/console/plugin-management The `plugin:install` command downloads and installs a plugin using its unique plugin code (AuthorName.PluginName) from the Winter marketplace. This command requires the installation to be bound to a project. Alternatively, `winter:up` can be used to run pending migrations for locally available plugin files. ```bash php artisan plugin:install ``` -------------------------------- ### SQL: Database Table Naming Convention Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Provides an example of the recommended database table naming convention in SQL. Tables should be prefixed with the author and plugin name, followed by an underscore and the table name (e.g., `acme_blog_xxx`). ```sql acme_blog_xxx ``` -------------------------------- ### Database Queries for Eager Loading Example in SQL Source: https://wintercms.com/docs/v1.2/docs/database/relations Provides example SQL queries demonstrating the efficiency of eager loading. It shows the initial query to fetch parent models ('books') and a subsequent query to fetch all related models ('authors') efficiently using an 'IN' clause. ```SQL select * from books select * from authors where id in (1, 2, 3, 4, 5, ...) ``` -------------------------------- ### Download and Install Winter CMS Theme Source: https://wintercms.com/docs/v1.2/docs/console/theme-management The `theme:install` command downloads and installs a theme using its unique code (AuthorName.ThemeName) from the Winter marketplace. Optionally, a specific directory can be provided for installation. The default installation directory is 'themes/authorname-themename'. ```bash php artisan theme:install [directory] ``` -------------------------------- ### Basic Winter CMS View File Example (HTML) Source: https://wintercms.com/docs/v1.2/docs/backend/controllers-ajax A simple example of a backend view file in Winter CMS, corresponding to an 'index' action method. View files use PHP syntax and can contain HTML. ```html

Hello World

``` -------------------------------- ### Install Winter CMS via Composer Source: https://wintercms.com/docs/v1.2/docs/architecture/using-composer This command installs Winter CMS using Composer. Replace `` with your desired directory name and optionally specify a version. Ensure you are in the project root when running commands. ```bash composer create-project wintercms/winter [version] # Example: # composer create-project wintercms/winter mywinter # or # composer create-project wintercms/winter ./ "dev-develop" ``` -------------------------------- ### Execute Code Before and After Tasks Source: https://wintercms.com/docs/v1.2/docs/plugin/scheduling Implement task hooks using the `before` and `after` methods to execute custom PHP code immediately before a task starts and after it completes. This is useful for setup and teardown operations. These methods are exclusively available for the `command` method. ```php $schedule->command('emails:send') ->daily() ->before(function () { // Task is about to start... }) ->after(function () { // Task is complete... }); ``` -------------------------------- ### Example SQL Query with Global Scope Applied Source: https://wintercms.com/docs/v1.2/docs/database/model This is an example of the SQL query that would be executed after applying the `AncientScope` to the `User` model. It shows the `WHERE` clause added by the global scope. ```sql select * from `users` where `created_at` < 0021-02-18 00:00:00 ``` -------------------------------- ### SQL Query Example with `secondOtherKey` Source: https://wintercms.com/docs/v1.2/docs/database/relations Illustrates the resulting SQL query generated by a `hasOneThrough` relationship when using `secondOtherKey` to join tables on non-standard keys. ```sql select `records`.* from `records` inner join `employees` on `employees`.`id` = `records`.`employee_id` where `employees`.`department_code` = `departments`.`code` ``` -------------------------------- ### Install Plugin or Theme using Composer Source: https://wintercms.com/docs/v1.2/docs/architecture/using-composer Installs a plugin or theme from Packagist into your Winter CMS project. The package will be added to your `composer.json` file. After installation, run `php artisan migrate` and `php artisan winter:mirror public --relative` to apply migrations and update the public directory. ```bash composer require # Example: # composer require winter/wn-pages-plugin ``` ```bash composer require "" # Example: # composer require winter/wn-pages-plugin "^2.0.0" ``` ```bash composer require --dev "" # Example: # composer require --dev winter/wn-builder-plugin "^2.0.0" ``` ```bash php artisan migrate && php artisan winter:mirror public --relative ``` -------------------------------- ### Layout with Description Configuration Source: https://wintercms.com/docs/v1.2/docs/cms/layouts An example of a layout template that includes optional configuration parameters, specifically a `description` which is used in the backend interface. The core structure with `{% page %}` remains the same. ```twig description = "Basic layout example" == {% page %} ``` -------------------------------- ### Get All Configuration Options Source: https://wintercms.com/docs/v1.2/docs/snowboard/extras Retrieves the entire configuration object, which includes merged values from defaults, data attributes, and local overrides. The `get()` method without arguments returns this complete configuration object. ```javascript this.config.get(); // Returns an object of all configuration options and their values. ``` -------------------------------- ### Install Composer in Winter CMS Source: https://wintercms.com/docs/v1.2/docs/architecture/using-composer If your `composer.json` file is missing, copy the latest version from GitHub into your project root and run `composer install`. Be aware that modifying files in the `modules` directory directly may lead to overwrites during updates. ```bash composer install ``` -------------------------------- ### Manage systemd Queue Worker Service Lifecycle Source: https://wintercms.com/docs/v1.2/docs/services/queues These commands demonstrate how to manage the lifecycle of a systemd user service for the queue worker. This includes enabling the service to start on boot, reloading configuration after changes, and starting, stopping, or restarting the service. These are standard systemd user commands. ```bash systemctl --user edit --force --full queue-worker.service ``` ```bash systemctl --user enable queue-worker.service ``` ```bash systemctl --user daemon-reload ``` ```bash systemctl --user start queue-worker.service ``` ```bash systemctl --user stop queue-worker.service ``` ```bash systemctl --user restart queue-worker.service ``` -------------------------------- ### Schedule a Console Command Source: https://wintercms.com/docs/v1.2/docs/plugin/scheduling This example shows how to schedule a console command to run on a daily basis. It utilizes the 'command' method provided by the scheduler. ```php $schedule->command('cache:clear')->daily(); ``` -------------------------------- ### Get Installed Winter Version Source: https://wintercms.com/docs/v1.2/docs/console/setup-maintenance The `winter:version` command displays the installed Winter CMS version by checking a central manifest and verifying file integrity. It alerts if system files have been modified. Use the `--changes` flag to list modified files or `--only-version` (`-o`) to retrieve just the version number for scripts. ```bash php artisan winter:version [--changes] [--only-version] ``` -------------------------------- ### Prepend and Append to File Source: https://wintercms.com/docs/v1.2/docs/services/filesystem-cdn Shows how to add content to the beginning of a file using Storage::prepend() and to the end using Storage::append(). ```php Storage::prepend('file.log', 'Prepended Text'); Storage::append('file.log', 'Appended Text'); ``` -------------------------------- ### Remove Demo Plugin and Theme with Winter CMS Source: https://wintercms.com/docs/v1.2/docs/console/setup-maintenance The `winter:fresh` Artisan command is used to remove the default demo plugin and theme from a Winter CMS installation. This command is useful for cleaning up a new installation or preparing for a production environment. ```bash php artisan winter:fresh ``` -------------------------------- ### Using env() Helper for Configuration Values Source: https://wintercms.com/docs/v1.2/docs/setup/configuration Demonstrates how configuration values are accessed using the `env()` helper function after converting to DotEnv format. The first argument is the environment variable key, and the second is an optional default value. ```php 'debug' => env('APP_DEBUG', true), ``` -------------------------------- ### Plugin Registration with Details and Components (PHP) Source: https://wintercms.com/docs/v1.2/docs/plugin/registration This snippet demonstrates a typical Plugin registration file in PHP for Winter CMS. It includes the required `pluginDetails` method to provide metadata about the plugin and the `registerComponents` method to register frontend components. ```php 'Blog Plugin', 'description' => 'Provides some really cool blog features.', 'author' => 'ACME Corporation', 'icon' => 'icon-snowflake-o' ]; } public function registerComponents() { return [ 'Acme\Blog\Components\Post' => 'blogPost' ]; } } ``` -------------------------------- ### PHP: Global Event Firing Example Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Demonstrates how to fire a global event in PHP using the `Event::fire()` method. The example shows firing a global event named `cms.page.end`. Global events are typically prefixed with the module or plugin name. ```php // For global events, it is prefixed with the module or plugin code Event::fire('cms.page.end'); ``` -------------------------------- ### Implementing Input Suggestion Methods in PHP Console Commands Source: https://wintercms.com/docs/v1.2/docs/console/introduction These examples show how to implement suggestion methods for command arguments and options in PHP. The `suggestMyArgumentValues` method provides suggestions for the 'myArgument' argument based on other input, while `suggestPackageOptions` suggests package names for the 'package' option by querying the database. These methods leverage the `ProvidesAutocompletion` trait (included by default in `WinterStormConsoleCommand`). ```php // ... /** * Example implementation of a suggestion method for the "myArgument" argument */ public function suggestMyArgumentValues(string $value = null, array $allInput): array { if ($allInput['arguments']['dependent'] === 'matches') { return ['some', 'suggested', 'values']; } return ['all', 'values']; } /** * Example implementation of a suggestion method for the "package" option */ public function suggestPackageOptions(string $value = null, array $allInput): array { return Package::all()->pluck('name')->all(); } // ... ``` -------------------------------- ### Theme Subdirectory Structure Example Source: https://wintercms.com/docs/v1.2/docs/cms/themes Demonstrates how Winter CMS supports single-level subdirectories for pages, partials, and content files to improve organization. Assets can have any structure. ```treeview themes `-- website |-- pages | |-- home.htm | `-- blog # Subdirectory | |-- archive.htm | `-- category.htm |-- partials | |-- sidebar.htm | `-- blog # Subdirectory | `-- category-list.htm `-- content |-- footer-contacts.txt `-- home # Subdirectory `-- intro.htm ``` -------------------------------- ### PHP: Local Event Firing Example Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Illustrates how to fire a local event in PHP using the `$this->fireEvent()` method. The example shows firing a local event named `page.end`. Local events do not require a prefix and are typically used for internal class communication. ```php // For local events, the prefix is not required $this->fireEvent('page.end'); ``` -------------------------------- ### Daemon Queue Worker Commands (Bash) Source: https://wintercms.com/docs/v1.2/docs/services/queues These commands start queue workers in daemon mode, which process jobs without restarting the framework for each job, leading to reduced CPU usage. The examples show starting a daemon worker with specified connection, sleep duration, and retry attempts. ```bash php artisan queue:work connection ``` ```bash php artisan queue:work connection --sleep=3 ``` ```bash php artisan queue:work connection --sleep=3 --tries=3 ``` -------------------------------- ### Make and Return a View (PHP) Source: https://wintercms.com/docs/v1.2/docs/services/response-view Create and return a view to the browser using the View::make method. It requires a 'path hint' for the view and an array of data to pass to it. ```PHP return View::make('acme.blog::greeting', ['name' => 'Charlie']); ``` -------------------------------- ### PHP Unit Test Case Example for Winter CMS Source: https://wintercms.com/docs/v1.2/docs/plugin/unit-testing An example of a PHP unit test class for a Winter CMS plugin. Test case classes must extend `System\Tests\Bootstrap\TestCase`, and test methods must be public and prefixed with `test` or annotated with `@test`. This class demonstrates basic test structure and assertion requirements. ```php get('file.jpg') ``` -------------------------------- ### View File Naming Conventions Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Rules for naming view files in WinterCMS. Partial views start with an underscore. Controller and Layout views do not. Underscores substitute for slashes (folders/namespaces), and dashes substitute for spaces. ```php index_fancy-layout.php <== Index\Fancy layout form-with-sidebar.php <== Form with sidebar _field-container.php <== Field container (partial) _field_baloon-selector.php <== Field\Baloon Selector (partial) ``` -------------------------------- ### Simplest Layout Example Source: https://wintercms.com/docs/v1.2/docs/cms/layouts Demonstrates the most basic layout structure in Winter CMS, including the HTML, BODY tags and the essential `{% page %}` tag for rendering page content. This serves as a foundational template for all pages. ```twig {% page %} ``` -------------------------------- ### Register Console Command via init.php (PHP) Source: https://wintercms.com/docs/v1.2/docs/console/introduction This example shows an alternative method for registering a console command by placing registration logic in an `init.php` file within the plugin directory. It utilizes the `Artisan::registerCommand` method to achieve this. ```php Artisan::registerCommand(new \MyAuthor\MyPlugin\Console\MyCommand()); ``` -------------------------------- ### Create a Collection Instance in PHP Source: https://wintercms.com/docs/v1.2/docs/services/collections Shows how to create a new `Winter\Storm\Support\Collection` instance by passing an array to its constructor. This is the fundamental way to begin using the collection's features. ```php $collection = new Winter\Storm\Support\Collection([1, 2, 3]); ``` -------------------------------- ### Retrieve a request URI segment Source: https://wintercms.com/docs/v1.2/docs/services/request-input Gets a specific segment from the request URI based on its position (index). For example, segment(1) would retrieve the first part of the path after the domain. It returns a string or null if the segment does not exist. ```php $segment = Request::segment(1); ``` -------------------------------- ### PHP Class Naming Conventions Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Defines PHP class naming rules using PascalCase. Avoids underscores due to historical autoloading issues. Numbers are allowed if necessary but not at the start. Namespacing should be used for organization instead of underscores. ```php class MyJet {} namespace API; class Jet {} ``` -------------------------------- ### Image Resizer Usage Examples - PHP Source: https://wintercms.com/docs/v1.2/docs/services/image-resizing Demonstrates various ways to access and utilize the Image Resizer service in PHP. This includes using it within backend list columns, on File model instances, and directly via the ImageResizer class. Proper cache drivers are essential for this service to function correctly. ```php [ // 'label' => 'Resized Image', // 'type' => 'image', // 'path' => 'resized', // 'width' => 100, // 'height' => 100, // ], // Example using getThumb() on a model $model = new MyModel(); // Assuming MyModel has an 'image' relation to a File attachment $imageUrl = $model->image->getThumb(200, 150, ['mode' => 'crop']); // Example using the ImageResizer class directly use System\Classes\ImageResizer; $sourceImagePath = '/path/to/your/image.jpg'; $resizedImageUrl = ImageResizer::filterGetUrl($sourceImagePath, 300, 200, ['quality' => 85]); $resizer = new ImageResizer(); $anotherResizedUrl = $resizer->resize($sourceImagePath, 150, 150, ['mode' => 'fit']); ?> ``` -------------------------------- ### PHP: Accessing Extended Model Relationships Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Demonstrates how to access dynamically extended model relationships in PHP, using a prefixed name to avoid conflicts. This example shows accessing a `winter_forum_member` relationship on a `$user` object, which was likely defined using the plugin name as a prefix. ```php $user->winter_forum_member ``` -------------------------------- ### Configure Form Behavior with YAML (YAML) Source: https://wintercms.com/docs/v1.2/docs/backend/forms This example shows a typical configuration file (`config_form.yaml`) for the Form behavior. It specifies the form name, the model class, and the path to the form field definitions. It also includes basic settings for the create, update, and preview pages. ```yaml # =================================== # Form Behavior Config # =================================== name: Blog Category form: $/acme/blog/models/post/fields.yaml modelClass: Acme\Blog\Post create: title: New Blog Post update: title: Edit Blog Post preview: title: View Blog Post ``` -------------------------------- ### PHP Widget Rendering with Partial Source: https://wintercms.com/docs/v1.2/docs/backend/widgets Provides an example of a widget's `render()` method in PHP, which is responsible for generating the widget's markup by rendering a specified partial. ```php public function render() { return $this->makePartial('list'); } ``` -------------------------------- ### PHP: Combining Local and Global Event Results Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Shows how to combine the results from both local and global events in PHP using `array_merge`. This is useful when multiple events might return data that needs to be aggregated. The examples use `form.beforeRefresh` for local and `backend.form.beforeRefresh` for global events. ```php // Combine local and global event results $eventResults = array_merge( $this->fireEvent('form.beforeRefresh', [$saveData]), Event::fire('backend.form.beforeRefresh', [$this, $saveData]) ); ``` -------------------------------- ### PHP Vendor Namespace Naming Convention Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Defines the standard for vendor or author names within PHP namespaces for Winter CMS projects. Vendor names must start with an uppercase character and should not contain underscores or dashes, ensuring a consistent and professional namespace structure. ```php // Valid names: Acme.Blog WinterStorm.User Happygilmore.Golf // Invalid names: acme.blog winterStorm.user Happy_gilmore.Golf ``` -------------------------------- ### Extend Models in Plugin Boot Method (PHP) Source: https://wintercms.com/docs/v1.2/docs/plugin/registration The `boot()` method in a WinterCMS plugin is executed after all services are loaded and plugins are registered. It's ideal for extending models, backend controllers, or form widgets. This example shows how to add a `hasOne` relationship to the User model. ```PHP use Backend\Model\User; public function boot() { User::extend(function ($model) { $model->hasOne['author'] = ['Acme\Blog\Models\Author']; }); } ``` -------------------------------- ### Define Dynamic Dropdown Options Source: https://wintercms.com/docs/v1.2/docs/plugin/components This example shows how to define a 'dropdown' property with dynamic options. If the 'options' parameter is omitted, the component must provide a method named 'get[PropertyName]Options' to return the options list dynamically. The method should return an associative array of option values and labels. ```php public function defineProperties(): array { return [ 'country' => [ 'title' => 'Country', 'type' => 'dropdown', 'default' => 'us' ] ]; } public function getCountryOptions() { return ['us' => 'United states', 'ca' => 'Canada']; } ``` -------------------------------- ### PHP: Extending Model Relationships with Plugin Prefix Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Illustrates how to dynamically extend model relationships in PHP, particularly when dealing with models from other plugins. It's recommended to prefix added fields with at least the plugin name to avoid potential conflicts. The example shows extending the `User` model with a `forum_member` relationship. ```php User::extend(function ($model) { $model->hasOne['forum_member'] = ['Winter\Forum\Models\Member']; }); ``` -------------------------------- ### Logging Information with Log Facade in PHP Source: https://wintercms.com/docs/v1.2/docs/services/error-log Provides examples of how to log messages at different levels using the `Log` facade. It covers basic informational logging and demonstrates the eight RFC 5424 logging levels available: `emergency`, `alert`, `critical`, `error`, `warning`, `notice`, `info`, and `debug`. Contextual data can also be passed as an array to enrich log entries. ```php $user = User::find(1); Log::info('Showing user profile for user: '.$user->name); ``` ```php Log::emergency($error); Log::alert($error); Log::critical($error); Log::error($error); Log::warning($error); Log::notice($error); Log::info($error); Log::debug($error); ``` ```php Log::info('User failed to login.', ['id' => $user->id]); ``` -------------------------------- ### Implement 'onInit' Handler in Page/Layout PHP Source: https://wintercms.com/docs/v1.2/docs/ajax/handlers Shows how to define an `onInit` function in the PHP section of a page or layout. Code within this function executes before any AJAX handler is called during the page lifecycle. ```php function onInit() { // From a page or layout PHP code section } ``` -------------------------------- ### PHP Trailing Commas in Arrays Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Demonstrates the recommended use of trailing commas in multi-line arrays in PHP for Winter CMS projects. This practice simplifies version control diffs and maintenance, particularly for localization files. The example shows the preferred format with a trailing comma and the less recommended format without. ```php // Recommended: $items = [ 'apple', 'banana', 'orange', ]; // Not recommended: $items = [ 'apple', 'banana', 'orange' ]; ``` -------------------------------- ### Perform Redirect from Lifecycle Function (PHP) Source: https://wintercms.com/docs/v1.2/docs/cms/pages Demonstrates how to use the `Redirect` facade within a lifecycle function (`onStart`) to issue an HTTP redirect to a specified URL. This is commonly used for user authentication or directing to external resources. ```php public function onStart() { return Redirect::to('http://google.com'); } ``` -------------------------------- ### Valid and Invalid Model Scope Examples in PHP Source: https://wintercms.com/docs/v1.2/docs/architecture/developer-guide Demonstrates the correct and incorrect ways to define model scopes in PHP for WinterCMS. Valid scopes must return a `QueryBuilder` instance for chaining, while invalid ones might prematurely execute the query. Also shows a valid standalone method for retrieving data. ```php public function scopeWithValidUser(Builder $query, User $user) { return $query->where('user_id', $user->id); } // Invalid scope method public function scopeWithValidUser(Builder $query, User $user) { return $query->where('user_id', $user->id)->get(); } // Valid standalone method returning a collection public function getValidUser(User $user) { return $this->withValidUser($user)->get(); } ``` -------------------------------- ### Composer JSON for Publishing Plugins Source: https://wintercms.com/docs/v1.2/docs/architecture/using-composer An example composer.json file for a Winter CMS plugin intended for publication. It specifies package details like name, type, description, keywords, license, authors, and required dependencies such as PHP version and the composer/installers package. Ensure the package name starts with 'wn-' and ends with '-plugin' or '-theme'. ```composer.json { "name": "winter/wn-demo-plugin", "type": "winter-plugin", "description": "Demo Winter CMS plugin", "keywords": ["winter", "cms", "demo", "plugin"], "license": "MIT", "authors": [ { "name": "Winter CMS Maintainers", "url": "https://wintercms.com", "role": "Maintainer" } ], "require": { "php": ">=7.2", "composer/installers": "~1.0" } } ``` -------------------------------- ### Specifying Connection and Queue Priorities (Bash) Source: https://wintercms.com/docs/v1.2/docs/services/queues These commands show how to specify the queue connection the worker should use and how to set priorities for multiple queues. Jobs from the `high` queue will be processed before jobs from the `low` queue. ```bash php artisan queue:work --once connection ``` ```bash php artisan queue:work --once --queue=high,low ``` -------------------------------- ### Get Request Input with get(), input(), and post() Source: https://wintercms.com/docs/v1.2/docs/services/helpers These functions retrieve input data from the current request. `get()` restricts input to GET variables, `post()` restricts input to POST variables, and `input()` retrieves input from any request method. All functions accept an optional default value. ```php $value = get('key', $default = null); ``` ```php $value = input('key', $default = null); ``` ```php $value = post('key', $default = null); ``` -------------------------------- ### Load Component Property from URL Parameter (INI) Source: https://wintercms.com/docs/v1.2/docs/cms/components Example of initializing a component property ('maxItems') with a value from a URL parameter using the {{ :paramName }} syntax in Winter CMS INI configuration. ```ini [demoTodo] maxItems = {{ :maxItems }} == ... ``` -------------------------------- ### Input Retrieval (GET) Source: https://wintercms.com/docs/v1.2/docs/services/helpers Obtains an input item from the request, restricted to GET variables only. ```APIDOC ## `get()` ### Description Obtains an input item from the request, restricted to GET variables only. ### Method `get(string $key, $default = null): mixed` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $value = get('key', $default); ``` ### Response #### Success Response (200) Returns the value of the specified GET parameter, or the default value if it does not exist. #### Response Example ```json { "inputValue": "some_value" } ``` ``` -------------------------------- ### Create and Drop Database Tables with Migrations in PHP Source: https://wintercms.com/docs/v1.2/docs/database/structure Demonstrates how to define a migration class in PHP to create and drop database tables. It includes methods for adding columns and specifying table engines, utilizing the Schema facade and its create and drop methods. ```PHP engine = 'InnoDB'; $table->increments('id'); $table->string('title'); $table->string('slug')->index(); $table->text('excerpt')->nullable(); $table->text('content'); $table->timestamp('published_at')->nullable(); $table->boolean('is_published')->default(false); $table->timestamps(); }); } public function down() { Schema::drop('winter_blog_posts'); } } ``` -------------------------------- ### Install Node Dependencies using NPM Utilities Source: https://wintercms.com/docs/v1.2/docs/console/asset-node-utilities Installs Node.js dependencies for a specified package or the project root. Supports installing to devDependencies using the --dev flag. Requires npm v7.0 or higher. ```bash php artisan npm:install ``` ```bash php artisan npm:install acme.plugin is-odd ``` ```bash php artisan npm:install acme.plugin is-odd is-even ``` ```bash php artisan npm:install acme.plugin is-odd is-even --dev ``` ```bash php artisan npm:install is-odd is-even ``` -------------------------------- ### Install Node Dependencies for Vite Packages Source: https://wintercms.com/docs/v1.2/docs/console/asset-compilation-vite Installs Node dependencies for all registered Vite packages in the project. It adds packages to `package.json` and runs `npm install`. Optionally, you can specify individual packages using `-p` or a custom npm path using `--npm`. ```bash php artisan vite:install [-p ] [--npm ] ``` -------------------------------- ### Partial `onStart` Lifecycle Function in Winter CMS Source: https://wintercms.com/docs/v1.2/docs/cms/partials Explains the `onStart` function within a partial's PHP section. This function executes before the partial renders and before its components are processed. It can be used to set variables for the Twig environment and load assets. ```php == function onStart() { $this['hello'] = "Hello world!"; /** * Variables that are already present on the page for Twig to use * can be accessed through the embedded controller instance. * If this partial was rendered by calling {% partial customVar="test" %} * then you could access that value with the following: */ $this->controller->vars['customVar']; /** * Partial code sections also have access to the addJs() / addCss() asset * loading methods which include support for deduplicating asset references * which means that if you have a block-based system for editing theme content * using grouped repeaters and a particular block partial requires CSS or JS * dependencies, they can be loaded directly in the partial that uses them. */ $this->addJs('https://cdn.example.com/js/vendor.js'); $this->addCss('https://cdn.example.com/css/vendor.css'); } ==

{{ hello }}

``` -------------------------------- ### List Installed Plugins in Winter CMS Source: https://wintercms.com/docs/v1.2/docs/console/plugin-management The `plugin:list` command generates a table displaying all installed plugins in your Winter CMS. It includes details such as the installed version, whether the plugin is enabled or disabled, and if its updates are frozen. Each plugin is identified by its code, which can be used for other plugin management commands. ```bash php artisan plugin:list ``` -------------------------------- ### Implement 'init' Method in Component/Widget Class (PHP) Source: https://wintercms.com/docs/v1.2/docs/ajax/handlers Demonstrates defining an `init` method within a component or backend widget class. This method serves the same purpose as `onInit` but is specific to the lifecycle of that component or widget. ```php function init() { // From a component or widget class } ``` -------------------------------- ### Create Directory Source: https://wintercms.com/docs/v1.2/docs/services/filesystem-cdn The Storage::makeDirectory() method creates a directory, including any necessary parent directories. ```php Storage::makeDirectory($directory); ``` -------------------------------- ### Install Node Dependencies for Mix Packages Source: https://wintercms.com/docs/v1.2/docs/console/asset-compilation-mix This command installs Node dependencies for all registered Mix packages in your Winter CMS project. It updates the root `package.json` with package workspaces and runs `npm install`. You can specify individual packages using the `-p` or `--package` flag. The `--npm` flag allows specifying a custom path to the npm executable. ```bash php artisan mix:install [-p ] [--npm ] ``` ```bash php artisan mix:install -p acme.example ``` ```bash php artisan mix:install -p acme.example -p acme.blog ``` -------------------------------- ### Registering and Booting Laravel Package Configuration in Winter CMS Source: https://wintercms.com/docs/v1.2/docs/architecture/using-composer This snippet demonstrates how to register and boot configuration for Laravel packages within a Winter CMS plugin. It iterates through configured packages, applies their settings, and ensures compatibility with Winter CMS's plugin-centric design. Dependencies include the Config facade. ```php public function bootPackages() { // Get the namespace code of the current plugin $pluginNamespace = str_replace('\\', '.', strtolower(__NAMESPACE__)); // Locate the packages to boot $packages = \Config::get($pluginNamespace . '::packages'); // Boot each package foreach ($packages as $name => $options) { // Apply the configuration for the package if ( !empty($options['config']) && !empty($options['config_namespace']) ) { Config::set($options['config_namespace'], $options['config']); } } } ``` ```php return [ // Laravel Package Configuration 'packages' => [ 'packagevendor/packagename' => [ // The accessor for the config item, for example, // to access via Config::get('purifier.' . $key) 'config_namespace' => 'purifier', // The configuration file for the package itself. // Copy this from the package configuration. 'config' => [ 'encoding' => 'UTF-8', 'finalize' => true, 'cachePath' => storage_path('app/purifier'), 'cacheFileMode' => 0755, ], ], ], ]; ``` -------------------------------- ### List Installed Winter CMS Themes Source: https://wintercms.com/docs/v1.2/docs/console/theme-management The `theme:list` command displays all themes currently installed in the Winter CMS project. It also indicates whether each listed theme is the active one. ```bash php artisan theme:list ``` -------------------------------- ### Response Creation Source: https://wintercms.com/docs/v1.2/docs/services/helpers Creates a response instance or obtains an instance of the response factory. ```APIDOC ## `response()` ### Description Creates a response instance or obtains an instance of the response factory. ### Method `response(string $content = '', int $status = 200, array $headers = []): IlluminateHttpResponse|IlluminateHttpJsonResponse` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Plain text response return response('Hello World', 200, $headers); // JSON response return response()->json(['foo' => 'bar'], 200, $headers); ``` ### Response #### Success Response (200) Returns a `Response` or `JsonResponse` instance. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- ### Pushing a Job onto the Queue (PHP) Source: https://wintercms.com/docs/v1.2/docs/services/queues Demonstrates how to push a new job onto the queue using the `Queue::push` method. The first argument is the job class name, and the second is an array of data to be passed to the handler. ```php Queue::push('SendEmail', ['message' => $message]); ``` -------------------------------- ### Render Component Partial from PHP Source: https://wintercms.com/docs/v1.2/docs/plugin/components Demonstrates how to programmatically render component partials within PHP code using the `renderPartial` method. It explains passing view variables and how path resolution works with the '@' prefix. ```php $content = $this->renderPartial('@component-partial.htm'); $content = $this->renderPartial('@component-partial.htm', [ 'name' => 'John Smith' ]); ``` ```php function onGetTemplate() { return ['#someDiv' => $this->renderPartial('@component-partial.htm')]; } ``` ```php public function onRun() { $content = $this->renderPartial('@default.htm'); return Response::make($content)->header('Content-Type', 'text/xml'); } ``` -------------------------------- ### Retrieve the request method Source: https://wintercms.com/docs/v1.2/docs/services/request-input Gets the HTTP method used for the current request (e.g., GET, POST). It also provides a way to check if the request method matches a specific type. It returns a string or a boolean. ```php $method = Request::method(); if (Request::isMethod('post')) { // } ``` -------------------------------- ### Scaffolding a New Console Command in PHP Source: https://wintercms.com/docs/v1.2/docs/console/introduction This code demonstrates the basic structure of a WinterCMS console command. It includes defining the command's default name, signature with arguments and options, description, and the core `handle` method where the command's logic resides. The `handle` method's return value indicates success (0) or failure (1). ```php argument("myArgument")} {--myOptionFlag : Defines a custom path to the "npm" binary}'; /** * @var string The console command description. */ protected $description = 'Install Node.js dependencies required for mixed assets'; /** * Execute the console command. * @return int */ public function handle(): int { $this->output->writeln('Hello world!'); return 0; // return 1 if an error occurs } } ``` -------------------------------- ### Use Multiple Instances of Same Component (INI) Source: https://wintercms.com/docs/v1.2/docs/cms/components Shows how to define multiple instances of the same component ('demoTodo') on a single page using distinct aliases ('todoA', 'todoB') in Winter CMS INI configuration. ```ini [demoTodo todoA] maxItems = 10 [demoTodo todoB] maxItems = 20 ``` -------------------------------- ### Dynamic Syntax Parser Initialization and View Mode Source: https://wintercms.com/docs/v1.2/docs/services/parser Initializes the Dynamic Syntax parser and demonstrates rendering in view mode. The parser can be initialized with template content and rendered to display default text or text with variables. ```php use Winter\Storm\Parse\Syntax\Parser as SyntaxParser; $content = "

{text name=\"websiteName\" label=\"Website Name\"}Our wonderful website{/text}

"; $syntax = SyntaxParser::parse($content); // Render with default text echo $syntax->render(); // Output:

Our wonderful website

// Render with variables echo $syntax->render(['websiteName' => 'Winter CMS']); // Output:

Winter CMS

``` ```php echo $syntax->toTwig(); // Output:

{{ websiteName }}

``` -------------------------------- ### Retrieve Item by Key with get() Source: https://wintercms.com/docs/v1.2/docs/services/collections The `get` method retrieves an item from a collection by its key. If the key is not found, it returns `null` by default. Optionally, a default value or a callback function can be provided to handle cases where the key does not exist, offering flexible data retrieval. ```php $collection = new Collection(['name' => 'peter', 'platform' => 'winter']); $value = $collection->get('name'); // peter ``` ```php $collection = new Collection(['name' => 'peter', 'platform' => 'winter']); $value = $collection->get('foo', 'default-value'); // default-value ``` ```php $collection->get('email', function () { return 'default-value'; }); // default-value ```