### Makefile Command Examples
Source: https://yiisoft.github.io/docs/guide/tutorial/docker.html
Examples of passing arguments to Makefile commands for package installation and test execution.
```sh
make composer require yiisoft/yii-db-mysql
```
```sh
make test -- Unit
```
--------------------------------
### Start the server
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-swoole.html
Execute the entry script to start the Swoole server.
```bash
php server.php
```
--------------------------------
### Start built-in server
Source: https://yiisoft.github.io/docs/guide/start/creating-project.html
Starts the local development server on the specified port.
```sh
./yii serve --port=80
```
--------------------------------
### Install a local package
Source: https://yiisoft.github.io/docs/guide/structure/package.html
Install a package defined in a local repository.
```sh
composer require vendor/blog
```
--------------------------------
### Install view packages
Source: https://yiisoft.github.io/docs/guide/views/view.html
Commands to install the core view package and the web-specific renderer.
```sh
composer require yiisoft/view
```
```sh
composer require yiisoft/yii-view-renderer
```
--------------------------------
### Install Swoole extension
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-swoole.html
Install the Swoole extension via PECL.
```bash
pecl install swoole
```
--------------------------------
### Install Widget Packages
Source: https://yiisoft.github.io/docs/guide/views/widget.html
Commands to install the core widget package and the collection of ready-made widgets.
```bash
composer require yiisoft/widget
```
```bash
composer require yiisoft/yii-widgets
```
--------------------------------
### Install migration package
Source: https://yiisoft.github.io/docs/guide/databases/db-migrations.html
Command to install the yiisoft/db-migration package via composer.
```shell
make composer require yiisoft/db-migration
```
--------------------------------
### Install View Renderer Package
Source: https://yiisoft.github.io/docs/guide/views/view-injections.html
Install the required package via composer.
```sh
composer require yiisoft/yii-view-renderer
```
--------------------------------
### Install dependencies
Source: https://yiisoft.github.io/docs/guide/rest/quick-start.html
Install the required packages for HTTP input handling, request body parsing, and data responses.
```shell
make composer require yiisoft/input-http yiisoft/request-body-parser yiisoft/data-response
```
--------------------------------
### Install security package
Source: https://yiisoft.github.io/docs/guide/security/cryptography.html
Command to install the required security library via Composer.
```bash
composer install yiisoft/security
```
--------------------------------
### Build and start Docker environment
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-frankenphp.html
Commands to rebuild the Docker image and start the environment after configuration changes.
```shell
make build
make up
```
--------------------------------
### Implement migration logic
Source: https://yiisoft.github.io/docs/guide/databases/db-migrations.html
Example implementation of the up() method to create a database table.
```php
columnBuilder();
$b->createTable('news', [
'id' => $cb::uuidPrimaryKey(),
'title' => $cb::string()->notNull(),
'content' => $cb::text(),
]);
}
```
--------------------------------
### Install i18n packages
Source: https://yiisoft.github.io/docs/guide/tutorial/i18n.html
Install the PHP-file message storage and the extractor for development.
```sh
composer require yiisoft/translator-message-php
```
```sh
composer require --dev yiisoft/translator-extractor
```
--------------------------------
### Install Dependencies for Production
Source: https://yiisoft.github.io/docs/guide/tutorial/performance-tuning.html
Run this command to install dependencies with an optimized autoloader and without development packages.
```shell
composer install --optimize-autoloader --no-dev
```
--------------------------------
### Define environment variables
Source: https://yiisoft.github.io/docs/cookbook/deployment/docker-swarm-caddy.html
Example environment file for database configuration.
```text
DB_HOST=db
DB_NAME=myapp
DB_USER=myapp
DB_PASSWORD=secure_password_here
```
--------------------------------
### Start Docker services
Source: https://yiisoft.github.io/docs/cookbook/deployment/angie-docker-proxy.html
Use this command to start the proxy and application containers defined in the docker-compose.yml file.
```bash
docker compose up -d
```
--------------------------------
### Initialize local configuration
Source: https://yiisoft.github.io/docs/guide/tutorial/docker.html
Command to create the local .env file from the example template.
```sh
cp .env.example .env
```
--------------------------------
### Install User Package
Source: https://yiisoft.github.io/docs/guide/security/authentication.html
Install the required yiisoft/user package via composer.
```shell
composer require yiisoft/user
```
--------------------------------
### Install UUID Package
Source: https://yiisoft.github.io/docs/guide/start/databases.html
Install the ramsey/uuid package to support UUID primary keys.
```shell
make composer require ramsey/uuid
```
--------------------------------
### Install Symfony Messenger
Source: https://yiisoft.github.io/docs/cookbook/third-party-integrations/symfony-messenger-integration-guide.html
Install the component via Composer.
```shell
composer require symfony/messenger
```
--------------------------------
### Install PostgreSQL Database Package
Source: https://yiisoft.github.io/docs/guide/start/databases.html
Install the required yiisoft/db-pgsql package via Composer.
```sh
make composer require yiisoft/db-pgsql:2.*
```
--------------------------------
### Start the server
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-roadrunner.html
Command to launch the RoadRunner server.
```bash
./rr serve
```
--------------------------------
### Install form package
Source: https://yiisoft.github.io/docs/guide/start/forms.html
Commands to install the form model package via composer.
```bash
composer require yiisoft/form-model
```
```bash
make composer require yiisoft/form-model
```
--------------------------------
### Example Application Directory Structure
Source: https://yiisoft.github.io/docs/guide/structure/overview.html
A visual representation of how to organize namespaces and classes under a 'Customer' context.
```text
App/
Customer/ <-- module namespace
Entity/
Customer.php <-- entity shared by "Profile" and "Checkout"
Profile/
Widget/
Gravatar.php
ProfileRepository.php <-- repository is usually specific to context
ProfileController.php <-- "Customer\Profile" entry point
ProductList/ <-- module namespace
Entity/ <-- entities specific to "Customer\ProductList"
Category.php
Product.php
ProductsListController.php <-- "Customer\ProductList" entry point
Checkout/ <-- module namespace
CheckoutController.php
```
--------------------------------
### Clone and install project in WSL
Source: https://yiisoft.github.io/docs/cookbook/working-on-windows.html
Commands to clone a repository and install dependencies within the WSL Linux filesystem.
```shell
cd ~
git clone https://github.com/yiisoft/app.git my-app
cd my-app
composer install
```
--------------------------------
### Install RoadRunner dependencies
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-roadrunner.html
Install the necessary Yii runner package and download the RoadRunner binary.
```bash
composer require yiisoft/yii-runner-roadrunner
```
```bash
./vendor/bin/rr get
```
--------------------------------
### Start Docker Development Containers
Source: https://yiisoft.github.io/docs/cookbook/configuring-xdebug.html
Initialize or restart development containers using the make command.
```shell
make up
```
--------------------------------
### Copy override configuration
Source: https://yiisoft.github.io/docs/guide/tutorial/docker.html
Command to create a local override file from the provided example.
```sh
cp docker/dev/override.env.example docker/dev/override.env
```
--------------------------------
### Install KV cache dependencies
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-roadrunner.html
Install the RoadRunner KV plugin and Yii cache package.
```bash
composer require spiral/roadrunner-kv yiisoft/cache
```
--------------------------------
### Install cache package
Source: https://yiisoft.github.io/docs/guide/caching/data.html
Command to install the required caching package via Composer.
```shell
composer require yiisoft/cache
```
--------------------------------
### Install HTTP driver
Source: https://yiisoft.github.io/docs/cookbook/sentry-integration.html
Command to install the necessary HTTP client dependencies for Sentry.
```shell
composer require php-http/httplug php-http/guzzle7-adapter --prefer-dist
```
--------------------------------
### Install Sentry package
Source: https://yiisoft.github.io/docs/cookbook/sentry-integration.html
Command to install the required Yii3 Sentry integration package.
```shell
composer require yiisoft/yii-sentry --prefer-dist
```
--------------------------------
### Verify Swoole installation
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-swoole.html
Check that the PHP environment correctly loads the Swoole extension.
```bash
php --ri swoole
```
--------------------------------
### Install data view package
Source: https://yiisoft.github.io/docs/cookbook/using-htmx-for-partial-reloads.html
Command to install the necessary data view package for GridView.
```shell
composer require yiisoft/yii-dataview
```
--------------------------------
### Create a view template
Source: https://yiisoft.github.io/docs/guide/views/view.html
Example of a PHP template file using Html::encode for safe output.
```php
The message is: = Html::encode($message) ?>
```
--------------------------------
### Install session package
Source: https://yiisoft.github.io/docs/guide/runtime/sessions.html
Use composer to add the session package to your project.
```shell
composer require yiisoft/session
```
--------------------------------
### Install Asset Package
Source: https://yiisoft.github.io/docs/guide/views/asset.html
Use Composer to add the asset management package to your project.
```bash
composer require yiisoft/assets
```
--------------------------------
### Installing RBAC PHP storage
Source: https://yiisoft.github.io/docs/guide/security/authorization.html
Install the required package to use PHP file storage for RBAC data.
```bash
composer require yiisoft/rbac-php
```
--------------------------------
### Example Twig template
Source: https://yiisoft.github.io/docs/guide/views/template-engines.html
A sample Twig template file demonstrating variable usage, conditionals, and loops.
```twig
{# Variable type hints for IDE support #}
{# @var user \App\Entity\User #}
{# @var posts \App\Entity\Post[] #}
{{ user.name }}
Email: {{ user.email }}
{% if posts is not empty %}
Recent Posts
{% for post in posts %}
{{ post.title }}
{{ post.excerpt }}
{% endfor %}
{% else %}
No posts available.
{% endif %}
```
--------------------------------
### Define Web test suite
Source: https://yiisoft.github.io/docs/guide/testing/environment-setup.html
Configures the Web suite to start a server and use PhpBrowser.
```yaml
actor: WebTester
extensions:
enabled:
- Codeception\Extension\RunProcess:
0: composer serve
sleep: 3
modules:
enabled:
- PhpBrowser:
url: http://127.0.0.1:8080
```
--------------------------------
### Start Built-in Server with Xdebug
Source: https://yiisoft.github.io/docs/cookbook/configuring-xdebug.html
Launch the Yii built-in server with the Xdebug trigger enabled.
```shell
./yii serve --xdebug
```
--------------------------------
### Using Widgets in Layouts
Source: https://yiisoft.github.io/docs/guide/views/widget.html
Example of invoking widgets within a standard PHP layout file.
```php
= NavigationWidget::widget() ?>
= UserMenuWidget::widget() ?>
= $content ?>
```
--------------------------------
### Install API Packages
Source: https://yiisoft.github.io/docs/guide/rest/quick-start.html
Adds necessary dependencies for JSON API support to an existing application.
```shell
composer require yiisoft/input-http yiisoft/request-body-parser yiisoft/data-response
```
--------------------------------
### Usage of Data List Widget
Source: https://yiisoft.github.io/docs/guide/views/widget.html
Example of how to invoke the DataListWidget within a view file.
```php
```
--------------------------------
### Layout Position Rendering
Source: https://yiisoft.github.io/docs/guide/views/script-style-meta.html
Example layout demonstrating where different resource positions are rendered in the HTML output.
```php
beginPage() ?>
head() ?>
beginBody() ?>
= $content ?>
endBody() ?>
endPage() ?>
```
--------------------------------
### Create project with Docker
Source: https://yiisoft.github.io/docs/guide/start/creating-project.html
Initializes a new project and sets up permissions using Docker and Make.
```sh
docker run --rm -it -v "$(pwd):/app" --user $(id -u):$(id -g) composer/composer create-project yiisoft/app your_project
sudo chown -R $(id -u):$(id -g) your_project
cd your_project
make composer update
```
--------------------------------
### Configure SSH access
Source: https://yiisoft.github.io/docs/cookbook/deployment/docker-swarm-caddy.html
Setup SSH keys and configuration for remote server access.
```bash
# Generate SSH key (if you don't have one)
ssh-keygen -t ed25519 -C "your_email@example.com"
# Copy the key to your server
ssh-copy-id user@your-server-ip
# Add the SSH host to your SSH config (~/.ssh/config)
cat >> ~/.ssh/config << EOF
Host docker-web
HostName your-server-ip
User user
IdentityFile ~/.ssh/id_ed25519
EOF
```
--------------------------------
### Setting Up a Complete Page
Source: https://yiisoft.github.io/docs/guide/views/script-style-meta.html
Demonstrates a full implementation of meta tags, CSS files, JavaScript files, and inline scripts within a view file.
```php
setTitle($title);
// Meta tags
$this->registerMeta(['name' => 'description', 'content' => $description]);
$this->registerMeta(['name' => 'keywords', 'content' => 'ecommerce, products, online shop']);
// Open Graph tags
$this->registerMeta(['property' => 'og:title', 'content' => $title]);
$this->registerMeta(['property' => 'og:description', 'content' => $description]);
$this->registerMeta(['property' => 'og:image', 'content' => $product['image']]);
// CSS files
$this->registerCssFile('/css/product.css');
$this->registerCssFile('/css/responsive.css', WebView::POSITION_HEAD, [
'media' => 'screen and (max-width: 768px)',
]);
// JavaScript files
$this->registerJsFile('/js/product-gallery.js', WebView::POSITION_END);
$this->registerJsFile('/js/shopping-cart.js', WebView::POSITION_END);
// JavaScript variables
$this->registerJsVar('productData', $product);
$this->registerJsVar('cartApiUrl', '/api/cart');
// Inline JavaScript
$this->registerJs('
document.addEventListener("DOMContentLoaded", function() {
initProductGallery();
initShoppingCart();
});
', WebView::POSITION_END);
// Page-specific styles
$this->registerCss('
.product-special {
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
padding: 20px;
border-radius: 10px;
}
', WebView::POSITION_HEAD);
?>
```
--------------------------------
### Create a home page test
Source: https://yiisoft.github.io/docs/guide/testing/end-to-end.html
Example of a Cest class testing basic page accessibility and content.
```php
wantTo('home page works.');
$I->amOnPage('/');
$I->expectTo('see page home.');
$I->see('Hello!');
}
}
```
--------------------------------
### Define Configuration Plugin Options
Source: https://yiisoft.github.io/docs/guide/concept/configuration.html
Example of a configuration file defining source directories, config groups, and environment-specific overrides.
```php
return [
'config-plugin-options' => [
'source-directory' => 'config',
],
'config-plugin' => [
'params' => 'common/params.php',
'params-web' => [
'$params',
'web/params.php',
],
'params-console' => [
'$params',
'console/params.php',
],
'bootstrap' => 'common/bootstrap.php',
'bootstrap-web' => '$bootstrap',
'bootstrap-console' => '$bootstrap',
'di' => 'common/di/*.php',
'di-web' => [
'$di',
'web/di/*.php',
],
'di-console' => '$di',
'di-delegates' => [],
'di-delegates-console' => '$di-delegates',
'di-delegates-web' => '$di-delegates',
'di-providers' => [],
'di-providers-web' => '$di-providers',
'di-providers-console' => '$di-providers',
'events' => [],
'events-web' => '$events',
'events-console' => '$events',
'routes' => 'common/routes.php',
],
'config-plugin-environments' => [
Environment::DEV => [
'params' => [
'environments/dev/params.php',
],
],
Environment::TEST => [
'params' => [
'environments/test/params.php',
],
],
Environment::PROD => [
'params' => [
'environments/prod/params.php',
],
],
],
];
```
--------------------------------
### Create project with Composer
Source: https://yiisoft.github.io/docs/guide/start/creating-project.html
Initializes a new project from the minimal Yii template using Composer.
```sh
composer create-project yiisoft/app your_project
```
--------------------------------
### Manually setting up a listener provider
Source: https://yiisoft.github.io/docs/guide/concept/events.html
Create a listener provider and dispatcher manually for package-level code or testing purposes.
```php
use Yiisoft\EventDispatcher\Dispatcher\Dispatcher;
use Yiisoft\EventDispatcher\Provider\ListenerCollection;
use Yiisoft\EventDispatcher\Provider\Provider;
$listeners = (new ListenerCollection())
->add(static function (UserSignedUp $event): void {
// Send a welcome email.
});
$provider = new Provider($listeners);
$dispatcher = new Dispatcher($provider);
$dispatcher->dispatch(new UserSignedUp($form));
```
--------------------------------
### Install PSR-7 converter
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-swoole.html
Install the required package to convert Swoole requests and responses to PSR-7 format.
```shell
composer require ilexn/swoole-convert-psr7
```
--------------------------------
### Install Debug API Package
Source: https://yiisoft.github.io/docs/guide/start/workflow.html
Install the development version of the debug API package via Composer.
```shell
composer require yiisoft/yii-debug-api:^3.0@dev
```
--------------------------------
### Creating a standalone console project
Source: https://yiisoft.github.io/docs/guide/tutorial/console-applications.html
Use this command to initialize a new console-only application using the official template.
```bash
composer create-project yiisoft/app-console your-project
```
--------------------------------
### Display Yii Development Tool help
Source: https://yiisoft.github.io/docs/internals/005-development-tool.html
Run the tool executable to view available commands and options for managing package repositories.
```bash
$ ./yii-dev
_ _ _ _
| | | |(_)(_) Development Tool
| |_| || || |
\__, ||_||_| for Yii 3.0
|___/
This tool helps with setting up a development environment for Yii 3 packages.
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
Available commands:
checkout-branch Creates, if not exists, and checkout a git branch
commit Add and commit changes into each package repository
install Install packages
lint Check packages according to PSR12 standard
pull Pull changes from package repositories
push Push changes into package repositories
replicate Copy files specified in replicate.php into each package
status Show git status of packages
update Update packages
```
--------------------------------
### Configure Multiple Database Connections
Source: https://yiisoft.github.io/docs/guide/start/databases.html
Setup multiple database connections using class aliases for distinct database instances.
```php
MainDatabase::class,
MainDatabase::class => [
'class' => Connection::class,
'__construct()' => [
'driver' => new Driver(
$params['app/db']['main']['dsn'],
$params['app/db']['main']['username'],
$params['app/db']['main']['password'],
),
],
],
```
--------------------------------
### Set up Docker Context
Source: https://yiisoft.github.io/docs/cookbook/deployment/docker-swarm-traefik.html
Methods to configure remote Docker access via context or environment variables.
```bash
docker context create swarm-prod --docker "host=ssh://docker-web"
```
```bash
export DOCKER_HOST=ssh://docker-web
```
--------------------------------
### Execute migration creation command
Source: https://yiisoft.github.io/docs/cookbook/custom-migration-template.html
Run the migration creation command to generate a new file using the configured template.
```shell
./yii migrate:create audit_log
```
--------------------------------
### Configuring Routes for GET and POST
Source: https://yiisoft.github.io/docs/guide/start/forms.html
Define routes that support both GET and POST methods to allow rendering and submitting the form.
```php
routes(
Route::get('/')
->action(Web\HomePage\Action::class)
->name('home'),
Route::methods([Method::GET, Method::POST], '/say')
->action(Web\Echo\Action::class)
->name('echo/say'),
),
];
```
--------------------------------
### Install Guzzle HTTP client
Source: https://yiisoft.github.io/docs/cookbook/making-http-requests.html
Use Composer to install Guzzle, which provides the necessary PSR-18 client and PSR-7 message implementations.
```shell
composer require guzzlehttp/guzzle
```
--------------------------------
### Send a GET request with PSR-18
Source: https://yiisoft.github.io/docs/cookbook/making-http-requests.html
Inject ClientInterface and RequestFactoryInterface to perform GET requests. Always check the HTTP status code as PSR-18 only throws exceptions for transport errors.
```php
*/
public function latest(string $owner, string $repository): array
{
$request = $this->requestFactory
->createRequest(
'GET',
sprintf(
'https://api.github.com/repos/%s/%s/releases/latest',
rawurlencode($owner),
rawurlencode($repository),
),
)
->withHeader('Accept', 'application/vnd.github+json');
try {
$response = $this->httpClient->sendRequest($request);
} catch (ClientExceptionInterface $e) {
throw new RuntimeException('GitHub request failed.', previous: $e);
}
if ($response->getStatusCode() !== 200) {
throw new RuntimeException(sprintf(
'GitHub returned HTTP %d.',
$response->getStatusCode(),
));
}
return json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
}
}
```
--------------------------------
### Environment unit test example
Source: https://yiisoft.github.io/docs/guide/testing/unit.html
A basic unit test class extending Codeception's Unit class to verify environment settings.
```php
translate('home.welcome');
$translator->translate('cart.items', ['count' => $itemCount]);
```
--------------------------------
### Install pdo_pgsql Extension
Source: https://yiisoft.github.io/docs/guide/start/databases.html
Add the pdo_pgsql extension to the install-php-extensions list in the Dockerfile.
```dockerfile
RUN install-php-extensions \
opcache \
mbstring \
intl \
dom \
ctype \
curl \
phar \
openssl \
xml \
xmlwriter \
simplexml \
pdo \
pdo_pgsql
```
--------------------------------
### Create Swoole server entry script
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-swoole.html
Define the server entry point, configuring the application runner and request/response conversion logic.
```php
setLevels([
LogLevel::EMERGENCY,
LogLevel::ERROR,
LogLevel::WARNING,
]),
],
),
new HtmlRenderer(),
),
);
$container = $runner->getContainer();
$application = $container->get(Application::class);
$errorCatcher = $container->get(ErrorCatcher::class);
$stateResetter = $container->get(StateResetter::class);
$serverRequestFactory = new SwooleServerRequestConverter(
$container->get(ServerRequestFactoryInterface::class),
$container->get(UriFactoryInterface::class),
$container->get(UploadedFileFactoryInterface::class),
$container->get(StreamFactoryInterface::class)
);
$server = new Server('0.0.0.0', 9501);
$server->on('start', static function (Server $server) use ($application) {
$application->start();
echo "Swoole http server is started at http://127.0.0.1:9501\n";
});
$server->on('request', static function (
Request $request,
Response $response
) use ($serverRequestFactory, $application, $errorCatcher, $stateResetter) {
try {
$psr7Request = $serverRequestFactory->createFromSwoole($request);
$psr7Response = $application->handle($psr7Request);
(new SwooleResponseConverter($response))->send($psr7Response);
} catch (Throwable $throwable) {
$handler = new ThrowableHandler($throwable);
$psr7Response = $errorCatcher->process($request, $handler);
(new SwooleResponseConverter($response))->send($psr7Response);
}
$application->afterEmit($psr7Response);
$stateResetter->reset();
});
$server->on('shutdown', static function (Server $server) use ($application) {
$application->shutdown();
});
$server->start();
```
--------------------------------
### Configure Doctrine Messenger
Source: https://yiisoft.github.io/docs/cookbook/third-party-integrations/symfony-messenger-integration-guide.html
Setup Doctrine dependencies and configuration for message transport.
```json
{
// ...
"require": {
// ...
"doctrine/orm": "^3",
"doctrine/dbal": "^4",
"symfony/cache": "^7"
},
}
```
```shell
composer install
```
```php
return [
// ...
'doctrine' => [
'paths' => [
],
'isDevMode' => false,
'connection' => [
'driver' => 'pdo_mysql',
'user' => 'site1',
'password' => 'secret',
'dbname' => 'site3'
]
],
];
```
```shell
composer require symfony/doctrine-messenger
```
```php
use App\Messages\MyMessage;
use App\Messages\MyMessageHandler;
use App\Services\ServiceProvider;
use Doctrine\DBAL\DriverManager;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMSetup;
use Doctrine\ORM\Proxy\ProxyFactory;
use Doctrine\ORM\Tools\Console\EntityManagerProvider;
use Doctrine\ORM\Tools\Console\EntityManagerProvider\SingleManagerProvider;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Messenger\Bridge\Doctrine\Transport\Connection;
use Symfony\Component\Messenger\Bridge\Doctrine\Transport\DoctrineTransport;
use Symfony\Component\Messenger\Command\ConsumeMessagesCommand;
use Symfony\Component\Messenger\Command\DebugCommand;
use Symfony\Component\Messenger\Command\FailedMessagesRemoveCommand;
use Symfony\Component\Messenger\Command\FailedMessagesRetryCommand;
use Symfony\Component\Messenger\Command\FailedMessagesShowCommand;
use Symfony\Component\Messenger\Command\SetupTransportsCommand;
use Symfony\Component\Messenger\Command\StatsCommand;
use Symfony\Component\Messenger\EventListener\StopWorkerOnRestartSignalListener;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\MessageBus;
use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
use Symfony\Component\Messenger\Middleware\SendMessageMiddleware;
use Symfony\Component\Messenger\RoutableMessageBus;
use Symfony\Component\Messenger\Transport\Sender\SendersLocator;
use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;
use Symfony\Contracts\Service\ServiceProviderInterface;
use Yiisoft\Aliases\Aliases;
use Yiisoft\Definitions\Reference;
class_alias(MessageBus::class, 'MyMessageBus');
```
--------------------------------
### Run ApacheBench Benchmark
Source: https://yiisoft.github.io/docs/guide/tutorial/performance-tuning.html
Use this command to perform load testing on the application with 1000 requests and 10 concurrent users.
```shell
ab -n 1000 -c 10 -t 10
```
--------------------------------
### Install Twig extension
Source: https://yiisoft.github.io/docs/guide/views/template-engines.html
Use Composer to add Twig support to your Yii3 application.
```bash
composer require yiisoft/view-twig
```
--------------------------------
### Build Production Image
Source: https://yiisoft.github.io/docs/cookbook/deployment/docker-swarm-traefik.html
Commands to build the production container image.
```bash
make prod-build
```
```bash
docker build --file docker/Dockerfile --target prod --pull -t ${IMAGE}:${IMAGE_TAG} .
```
--------------------------------
### Block Type Translation Configuration
Source: https://yiisoft.github.io/docs/internals/014-docs.html
Example configuration for translating block labels into German.
```json
{
"Note": "Hinweis",
"Tip": "Tipp",
"Important": "Wichtig",
"Warning": "Achtung",
"Caution": "Vorsicht"
}
```
--------------------------------
### Define basic composer.json metadata
Source: https://yiisoft.github.io/docs/guide/structure/designing-packages.html
Set up the package name, dependencies, and PSR-4 autoloading in the root composer.json file.
```json
{
"name": "vendor/blog",
"type": "library",
"description": "Blog integration for Yii applications",
"require": {
"php": ">=8.2",
"yiisoft/router": "^4.0"
},
"autoload": {
"psr-4": {
"Vendor\\Blog\\": "src/"
}
}
}
```
--------------------------------
### Implementing a Service Provider
Source: https://yiisoft.github.io/docs/guide/concept/configuration.html
Create a service provider by implementing Yiisoft\Di\ServiceProviderInterface to define services and extensions.
```php
use Psr\\Container\\ContainerInterface;
use Psr\\SimpleCache\\CacheInterface;
use Yiisoft\\Aliases\\Aliases;
use Yiisoft\\Cache\\Cache;
use Yiisoft\\Cache\\CacheInterface as YiiCacheInterface;
use Yiisoft\\Cache\\File\\FileCache;
use Yiisoft\\Di\\ServiceProviderInterface;
final readonly class CacheProvider implements ServiceProviderInterface
{
public function __construct(
private string $cachePath = '@runtime/cache'
)
{
}
public function getDefinitions(): array
{
return [
CacheInterface::class => function (ContainerInterface $container) {
$aliases = $container->get(Aliases::class);
return new FileCache($aliases->get($this->cachePath));
},
YiiCacheInterface::class => Cache::class,
];
}
public function getExtensions(): array
{
return [];
}
}
```
--------------------------------
### Define message files
Source: https://yiisoft.github.io/docs/guide/tutorial/i18n.html
Example structure and content for English and German translation files.
```text
messages/
├── de/
│ └── app.php
└── en-US/
└── app.php
```
```php
'Home',
'home.welcome' => 'Welcome to Yii3',
'cart.items' => '{count, plural, =0{No items} one{# item} other{# items}}',
];
```
```php
'Home',
'home.welcome' => 'Willkommen bei Yii3',
'cart.items' => '{count, plural, =0{Keine Artikel} one{# Artikel} other{# Artikel}}',
];
```
--------------------------------
### Initialize Docker Swarm
Source: https://yiisoft.github.io/docs/cookbook/deployment/docker-swarm-traefik.html
Initializes the server as a Docker Swarm manager.
```bash
docker swarm init --advertise-addr
```
--------------------------------
### Markdown template example
Source: https://yiisoft.github.io/docs/guide/views/template-engines.html
A sample Markdown template file used with the custom renderer.
```markdown
# Help: {{title}}
Welcome, {{username}}!
This is a Markdown template with **bold** and *italic* text.
- Feature 1
- Feature 2
- Feature 3
```
--------------------------------
### Define a form model
Source: https://yiisoft.github.io/docs/guide/start/forms.html
Example of a Form class extending FormModel with validation attributes.
```php
'screen and (max-width: 768px)'],
];
public array $depends = [
AppAsset::class,
];
}
```
--------------------------------
### Create Responding Middleware
Source: https://yiisoft.github.io/docs/guide/structure/middleware.html
Example of middleware that generates a response directly using a ResponseFactoryInterface.
```php
responseFactory->createResponse();
$response->getBody()->write('Hello!');
return $response;
}
}
```
--------------------------------
### Example directory structure for vertical slices
Source: https://yiisoft.github.io/docs/cookbook/organizing-code/structuring-by-use-case-with-vertical-slices.html
A directory layout demonstrating how to group models, services, and use-case specific actions within a feature-based structure.
```text
src/
└── Blog/
├── Model/
│ ├── Comment.php
│ ├── CommentRepository.php
│ ├── Post.php
│ └── PostRepository.php
├── Service/
│ └── MarkdownProcessor.php
├── UseCase/
│ ├── CreateComment/
│ │ ├── CreateCommentAction.php
│ │ ├── CreateCommentRequest.php
│ ├── CreatePost/
│ │ ├── CreatePostAction.php
│ │ ├── CreatePostRequest.php
│ ├── DeleteComment/
│ │ ├── DeleteCommentAction.php
│ │ ├── DeleteCommentRequest.php
│ ├── DeletePost/
│ │ ├── DeletePostAction.php
│ │ ├── DeletePostRequest.php
│ ├── ListComments/
│ │ ├── ListCommentsAction.php
│ ├── ListPosts/
│ │ ├── ListPostsAction.php
│ ├── UpdatePost/
│ │ ├── UpdatePostAction.php
│ │ ├── UpdatePostRequest.php
│ ├── ViewPost/
│ │ ├── ViewPostAction.php
│ ├── Rss/
│ │ ├── RssAction.php
| | ├── RssBuilder.php
```
--------------------------------
### Define a migration down method
Source: https://yiisoft.github.io/docs/guide/databases/db-migrations.html
Example of a down method implementation using the MigrationBuilder to drop a table.
```php
public function down(MigrationBuilder $b): void
{
$b->dropTable('news');
}
}
```
--------------------------------
### Inject Service into a Class
Source: https://yiisoft.github.io/docs/guide/concept/di-container.html
Example of a class consuming a service via constructor injection.
```php
final class MyAction
{
public function __construct(
private readonly MyServiceInterface $myService
) {
}
public function __invoke()
{
$this->myService->doSomething();
}
}
```
--------------------------------
### Install FrankenPHP runner
Source: https://yiisoft.github.io/docs/guide/tutorial/using-yii-with-frankenphp.html
Use Composer to add the FrankenPHP runner package to your Yii project.
```shell
composer require yiisoft/yii-runner-frankenphp
```
--------------------------------
### Loading Resources Conditionally
Source: https://yiisoft.github.io/docs/guide/views/script-style-meta.html
Shows how to register CSS and JavaScript based on application state or user roles.
```php
registerCssFile('/css/dark-theme.css');
} else {
$this->registerCssFile('/css/light-theme.css');
}
// Admin-specific resources
if ($isAdmin) {
$this->registerCssFile('/css/admin-toolbar.css');
$this->registerJsFile('/js/admin-functions.js');
}
// Role-based JavaScript configuration
$this->registerJsVar('userPermissions', [
'canEdit' => in_array($userRole, ['admin', 'editor']),
'canDelete' => $userRole === 'admin',
'canPublish' => in_array($userRole, ['admin', 'publisher']),
]);
?>
```