Yii3 - How to start

You are viewing revision #20 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#19)next (#21) »

(draft)

In Yii3 it is not as easy to start as it was with Yii2. You have to install and configure basic things on your own. Yii3 uses the modern approach based on independent packages and dependency injection, but it makes it harder for newcomers. I am here to show them ...

Note:

  • Instead of installing local WAMP- or XAMPP-server I will be using Docker.
  • Do not forget about a modern IDE like PhpStorm, which comes budled with all you will ever need.

Yii3 - How to start

  1. Running the demo application
  2. Adding DB into your project
  3. Enabling MariaDB (MySQL) and migrations
  4. Creating a migration
  5. Running the migrations
  6. Reading data from DB
  7. Seeding the database

Yii3 offers more basic applications: Web, Console, API. I will be using the API application:

Clone it like this:

.. and follow the docker instructions in the documentation.

If you don't have Docker, I recommend installing the latest version of Docker Desktop:

Running the demo application

You may be surprised that docker-compose.yml is missing in the root. Instead the "make" commands are prepared. If you run both basic commands as mentioned in the documentation:

  • make composer update
  • make up

... then the web will be available on URL

If you check the returned data you will see a <xml> inside the browser. In order to obtain JSON-response, paste the URL into Postman. (so called "content negotiation" does this auto-decision)

If you want to modify the data that was returned by the endpoint, just open the action-class (src/Api/IndexAction.php) and add one more element to the returned array.

Adding DB into your project

Your project now does not contain any DB. Let's add MariaDB and Adminer (DB browser) into file docker/dev/compose.yml:

In my case the resulting file looks like this:

services:
  app:
    container_name: yii3api_php
    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
    restart: unless-stopped
    depends_on:
      - db
    ports:
      - "${DEV_PORT:-80}:80"
    volumes:
      - ../:/app
      - ../runtime:/app/runtime
      - caddy_data:/data
      - caddy_config:/config
    tty: true
  db:
    image: mariadb:12.0.2-noble
    container_name: yii3api_db
    environment:
      MARIADB_ROOT_PASSWORD: root
      MARIADB_DATABASE: db
      MARIADB_USER: db
      MARIADB_PASSWORD: db
  adminer:
    image: adminer:latest
    container_name: yii3api_adminer
    environment:
      ADMINER_DEFAULT_SERVER: db
    ports:
      - ${DEV_ADMINER_PORT}:8080
    depends_on:
      - db
volumes:
  mariadb_data:

Plus add/modify these variables in file docker/.env

  • DEV_PORT=9080
  • DEV_ADMINER_PORT=9081

Then run following commands:

  • make down
  • make build
  • make up

Now you should see a DB browser on URL http://localhost:9081/?server=db&username=db&db=db

Login, server and pwd is defined in the snippet above.

If you type "docker ps" into your host console, you should see 3 running containers: yii3api_php, yii3api_adminer, yii3api_db.

The web will be, from now on, available on URL http://localhost:9080 which is more handy than just ":80" I think. (Later you may run 4 different projects at the same time and all cannot run on port 80)

Enabling MariaDB (MySQL) and migrations

Now when your project contains MariaDB, you may wanna use it in the code ...

Installing composer packages

After some time of searching you will discover you need to install these composer packages:

So you need to run following commands:

  • composer require yiisoft/db-mysql
  • composer require yiisoft/cache
  • composer require yiisoft/db-migration --dev

To run composer (or any other command inside your dockerized yii3 application) you have 4 options:

  • Make: The best solution is to prepend the composer commands with "make".

Other solutions:

  • If you have Composer running locally, you can call these commands directly on your computer. (I do not recommend)

  • You can SSH into your docker container and call it there as Composer is installed inside. In that case:

    • Find the name of the PHP container by typing "docker ps"
    • Call "docker exec -it {containerName} /bin/bash"
    • Now you are in the console of your php server and you can run composer.
  • If you are using PhpStorm, find the small icon "Services" in the left lower corner (looks ca like a cog wheel), find item "Docker-compose: app-api", inside click the "app" service, then "yii3api_php" container and then hit the button "terminal" on the righthand side.

Setting up composer packages

Follow their documentations. Quick links:

The documentations want you to create 2 files:

  • config/common/di/db-mysql.php
  • config/common/db.php
  • But you actually need only one. I recommend db-mysql.php

Note: If you want to create a file using commandline, you can use command "touch". For example "touch config/common/di/db-mysql.php"

Note: In the documentation the PHP snippets do not contain tag and declaration. Prepend it:

<?php
declare(strict_types=1);
Create folder for migrations
  • src/Migration

When this is done, call "composer du" or "make composer du" and then try "make yii list". You should see the migration commands.

Creating a migration

Run the command to create a migration:

  • make yii migrate:create user

Open the file and paste following content to the up() method:

$b->createTable('user', [
'id' => $b->primaryKey(),
'name' => $b->string()->notNull(),
'surname' => $b->string()->notNull(),
'username' => $b->string(),
'email' => $b->string()->notNull()->unique(),
'phone' => $b->string(),
'admin_enabled' => $b->boolean()->notNull()->defaultValue(false)->comment('Can user access the administration?'),
'vuejs_enabled' => $b->boolean()->notNull()->defaultValue(false)->comment('Can user access the mobile application?'),
'auth_key' => $b->string(32)->notNull()->unique(),
'access_token' => $b->string(32)->unique()->comment('For API purposes'),
'password_hash' => $b->string(),
'password_default' => $b->string(),
'password_vuejs_default' => $b->string(),
'password_vuejs_hash' => $b->string(),
'password_reset_token' => $b->string()->unique(),
'verification_token' => $b->string()->unique(),
'verified_at' => $b->dateTime(),
'status' => $b->smallInteger()->notNull()->defaultValue(100),
'created_by' => $b->integer(),
'updated_by' => $b->integer(),
'deleted_by' => $b->integer(),
'created_at' => $b->dateTime()->notNull()->defaultExpression('CURRENT_TIMESTAMP'),
'updated_at' => $b->dateTime(),
'deleted_at' => $b->dateTime(),
]);

The down() method should contain this:

$b->dropTable('user');

Running the migrations

Try to run "make yii migrate:up" and you will see error "could not find driver", because file "docker/Dockerfile" does not install the "pdo_mysql" extention. Add it to the place where "install-php-extensions" is called.

Then call:

  • make down
  • make build
  • make up

Now you will see error "Connection refused" It means you have to update dns, user and password in file "config/common/params.php" based on what is written in "docker/dev/compose.yml".

If you run "make yii migrate:up" it should work now and your DB should contain the first table. Check it via adminer: http://localhost:9081/?server=db&username=db&db=db

Reading data from DB

In Yii we were always using ActiveRecord and its models, but in Yii3 the package is not ready yet. The solution is to use existing class Yiisoft\Db\Query\Query.

Open class src/Api/IndexAction.php and modify it a little to return all users via your REST API. You have more options:

You can manually instantiate the Query object, but you need to provide the DB connection manually:

declare(strict_types=1);
namespace App\Api;
use App\Api\Shared\ResponseFactory;
use App\Shared\ApplicationParams;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Query\Query;

final class IndexAction
{
    public function __invoke(
        ResponseFactory     $responseFactory,
        ApplicationParams   $applicationParams,
        ConnectionInterface $db,
    ): ResponseInterface
    {
        $query = (new Query($db))
            ->select('*')
            ->from('user');
        return $responseFactory->success($query->all());
    }
}

Or you can use the DI container to provide you with the instance. I like this better as I can omit input parameters:

declare(strict_types=1);
namespace App\Api;
use App\Api\Shared\ResponseFactory;
use App\Shared\ApplicationParams;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Db\Query\Query;

final class IndexAction
{
    public function __invoke(
        ResponseFactory    $responseFactory,
        ApplicationParams  $applicationParams,
        ContainerInterface $container,
    ): ResponseInterface
    {
        $query = $container->get(Query::class)
            ->select('*')
            ->from('user');
        return $responseFactory->success($query->all());
    }
}

Now you can call the URL and see all the users. (If you entered some) http://localhost:9080

Note: You can also use Injector (and method $injector->make()) instead of ContainerInterface (and method $container->get()). Injector seems to allow you to pass input arguments if needed.

PS: The input parameter of new Query(ConnectionInterface $db) is automatically provided as it is defined in DI. See the file you created earlier above: config/common/di/db-mysql.php

Seeding the database

Seeding = inserting fake data.

You can technically create a migration or a command and insert random data manually. But you can also use the Faker. In that case I needed following dependencies:

  • composer require fakerphp/faker
  • composer require yiisoft/security (not only for generating random strings)

Now find the class HelloCommand.php, copy and rename it to SeedCommand.php

Inside you will need the instance of ConnectionInterface. It can be automatically provided by the DI (because you defifned it in config/common/di/db-mysql.php), you only need to create a new constructor and then use the instance in method execute():

namespace App\Console;

use Faker\Factory;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Security\Random;
use Yiisoft\Yii\Console\ExitCode;

#[AsCommand(
    name: 'seed',
    description: 'Run to seed the DB',
)]
final class SeedCommand extends Command
{
    public function __construct(
        private readonly ConnectionInterface $db
    )
    {
        parent::__construct();
    }

    protected function execute(
        InputInterface  $input,
        OutputInterface $output
    ): int
    {

        $faker = Factory::create();

        for ($i = 0; $i < 10; $i++) {
            $this->db->createCommand()
                ->insert('user', [
                    'name' => $faker->firstName(),
                    'surname' => $faker->lastName(),
                    'username' => $faker->userName(),
                    'email' => $faker->email(),
                    'auth_key' => Random::string(32),
                ])
                ->execute();
        }

        $output->writeln('Seeding DONE.');

        return ExitCode::OK;
    }
}

Register the new command in file config/console/commands.php.

You can also obtain the ConnectionInterface in the same way as you did it in IndexAction with the Query object. Just use ContainerInterface $container in the constructor instead of ConnectionInterface $db. Then you can call $db = $this->container->get(ConnectionInterface::class);.

1 0
2 followers
Viewed: 575 times
Version: 3.0
Category: Tutorials
Tags:
Written by: rackycz rackycz
Last updated by: rackycz rackycz
Created on: Oct 8, 2025
Last updated: 2 days ago
Update Article

Revisions

View all history