Revision #17 has been created by
rackycz on Oct 9, 2025, 7:59:30 AM with the memo:
edit
« previous (#16) next (#18) »
Changes
Title
unchanged
Yii3 - How to start
Category
unchanged
Tutorials
Yii version
unchanged
3.0
Tags
unchanged
Content
changed
[...]
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 Fake. 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():
```php
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(),
'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`.