Yii3 Web Application Template

repository·master·Indexed 18 days ago

https://github.com/yiisoft/app

A classic web application template for Yii3 designed as a starting point for new projects. It provides a structured environment with built-in support for local development, Docker, Codeception testing, and Psalm static analysis. The template includes configurations for development and production environments, including Docker Compose orchestration and a defined directory structure for source code, configuration, and assets.

Tokens
2.7K
Snippets
9
Records
10
Agent score
60%

What's inside yiisoft/app

  1. Understand the Yii3 application directory structure

    master

    The Yii3 web application template follows this directory structure:

    • assets/: Asset bundle source files.
    • config/: Configuration files.
      • common/: Common configuration and DI definitions.
      • console/: Console-specific configuration.
      • environments/: Environment-specific configuration (dev/test/prod).
      • web/: Web-specific configuration.
    • docker/: Docker-specific files.
    • public/: Files publicly accessible from the Internet.
      • assets/: Published/compiled assets.
      • index.php: Entry script.
    • runtime/: Files generated during runtime.
    • src/: Application source code.
      • Console/: Console commands.
      • Shared/: Code shared between web and console applications.
      • Web/: Web-specific code (actions, handlers, layout).
        • Shared/: Shared web components.
          • Layout/: Layout components and templates.
      • bootstrap.php: Application bootstrap (autoloading, environment setup).
      • Environment.php: Environment configuration class.
    • tests/: Codeception tests (Console, Functional, Unit, Web).
    • vendor/: Installed Composer packages.
    • Makefile: Config for make commands.
    • yii: Console application entry point.
  2. Run tests with Codeception

    master

    The template includes pre-configured Codeception tests.

    For Local Installation:

    1. Build the Codeception configuration.
    2. Start the application in the test environment in the background.
    3. Run the tests.

    For Docker Installation: Use the provided make commands.

    # Local installation
    ./vendor/bin/codecept build
    APP_ENV=test ./yii serve > ./runtime/yii.log 2>&1 &
    ./vendor/bin/codecept run
    
    # Docker installation
    make codecept build
    make codecept run
  3. Install the Yii3 web application locally

    master

    To install the Yii3 web application template on your local machine, use Composer. Ensure that Composer is executed with the same PHP version that will be used to run the application (PHP 8.2 - 8.5).

    1. Create the project using composer create-project.
    2. Navigate to the project directory.
    3. Copy the .env.example file to .env and configure your environment variables.
    4. Start the application using the ./yii serve command.

    By default, the application is accessible at http://localhost:8080 (or the URL printed to your console).

    composer create-project yiisoft/app myproject
    cd myproject
    cp .env.example .env
    ./yii serve
  4. Install and run the Yii3 web application with Docker

    master

    If you prefer using Docker, ensure you have Docker Compose version 2.24 or above installed.

    1. Fork and clone the repository.
    2. Run make composer update to prepare dependencies.
    3. Use make up to start the application.
    4. Use make open to open the app in your default browser.
    5. Use make down to stop the application.

    The application is available at http://localhost when running via Docker.

    cd myproject
    make composer update
    make up
    make open
    make down
  5. Configure the APP_HOST_PATH environment variable

    master

    The APP_HOST_PATH environment variable defines the absolute path on the host machine that corresponds to the project directory within the Docker container. This is used to map your local source code into the development environment.

    APP_HOST_PATH=/projects/yiisoft/app
  6. Configure Docker Compose for the application

    master

    The project provides a docker/compose.yml file to orchestrate services. The app service includes a configuration to allow the container to communicate with the host machine using the host.docker.internal hostname via the host-gateway driver. This is useful for connecting to services running on your local machine outside of Docker.

    Persistent data for the Caddy web server is managed via two named volumes: caddy_data and caddy_config.

    services:
      app: &appconfig
        extra_hosts:
          - "host.docker.internal:host-gateway"
    
    volumes:
      caddy_data:
      caddy_config:
  7. Configure production deployment with Docker Compose

    master

    The production environment uses a Docker Compose configuration that defines an app service designed for high availability and automated deployment.

    Environment Variables

    The configuration relies on several environment variables for image selection and host configuration:

    • ${IMAGE}: The Docker image name.
    • ${IMAGE_TAG}: The specific tag for the image.
    • ${PROD_HOST}: The hostname for the Caddy reverse proxy. Defaults to app.example.com if not provided.

    Environment Files

    Environment variables are loaded from the following files in order (later files override earlier ones):

    1. ./prod/.env (Required)
    2. ./prod/override.env (Optional)

    Deployment and Scaling

    The service is configured for production-grade deployment with the following settings:

    • Replicas: 2 instances are maintained.
    • Update Strategy: Uses start-first order (starts new containers before stopping old ones) with a 10s delay and a parallelism of 1. If an update fails, it triggers a rollback.
    • Rollback Strategy: Uses stop-first order.
    • Restart Policy: Restarts on failure with a 5s delay, up to 3 attempts within a 120s window.

    Networking and Reverse Proxy

    • The service connects to an external network named caddy_public.
    • It uses Caddy labels for automatic reverse proxy configuration. The caddy.reverse_proxy label is set to route traffic to upstreams on port 80.
    services:
      app:
        image: ${IMAGE}:${IMAGE_TAG}
        networks:
          - caddy_public
        volumes:
          - runtime:/app/runtime
          - caddy_data:/data
          - caddy_config:/config
        env_file:
          - path: ./prod/.env
          - path: ./prod/override.env
            required: false
        deploy:
          replicas: 2
          update_config:
            delay: 10s
            parallelism: 1
            order: start-first
            failure_action: rollback
            monitor: 10s
          rollback_config:
            parallelism: 0
            order: stop-first
          restart_policy:
            condition: on-failure
            delay: 5s
            max_attempts: 3
            window: 120s
          labels:
            caddy: ${PROD_HOST:-app.example.com}
            caddy.reverse_proxy: "{{upstreams 80}}"
    
    volumes:
      runtime:
    
    networks:
      caddy_public:
        external: true
  8. Configure the development environment with Docker Compose

    master

    The project provides a Docker Compose configuration for local development. The app service builds from docker/Dockerfile using the dev target.

    Environment Variables

    To customize the build and runtime behavior, you can provide the following environment variables:

    • UID: Sets the USER_ID build argument for the container user.
    • GID: Sets the GROUP_ID build argument for the container group.
    • DEV_PORT: Sets the host port mapping. Defaults to 80 if not specified.

    Environment Files

    The service loads environment variables from:

    1. ./dev/.env (Required)
    2. ./dev/override.env (Optional)

    Volume Mappings

    • ../:/app: Mounts the project root to /app in the container.
    • ../runtime:/app/runtime: Mounts the local runtime directory to /app/runtime for persistent application data.
    • caddy_data:/data: Persistent storage for Caddy data.
    • caddy_config:/config: Persistent storage for Caddy configuration.
    services:
      app:
        build:
          dockerfile: docker/Dockerfile
          context: ..
          target: dev
          args:
            USER_ID: ${UID}
            GROUP_ID: ${GID}
        env_file:
          - path: ./dev/.env
          - path: ./dev/override.env
            required: false
        ports:
          - "${DEV_PORT:-80}:80"
        volumes:
          - ../:/app
          - ../runtime:/app/runtime
          - caddy_data:/data
          - caddy_config:/config
        tty: true
  9. Run the HTTP application via HttpApplicationRunner

    master

    The application is bootstrapped and executed using the HttpApplicationRunner. This runner requires the application root path, debug mode status, event checking preference, and the current environment. It also configures a temporaryErrorHandler to handle errors during the early stages of the application lifecycle using a Logger with a StreamTarget and an HtmlRenderer.

    $runner = new HttpApplicationRunner(
        rootPath: $root,
        debug: Environment::appDebug(),
        checkEvents: Environment::appDebug(),
        environment: Environment::appEnv(),
        temporaryErrorHandler: new ErrorHandler(
            new Logger(
                [
                    (new StreamTarget())->setLevels([
                        LogLevel::EMERGENCY,
                        LogLevel::ERROR,
                        LogLevel::WARNING,
                    ]),
                ],
            ),
            new HtmlRenderer(),
        ),
    );
    $runner->run();