Revision #21 was created by rackycz on Oct 9, 2025, 10:14:33 AM.
edit
Content
[...]
}
```
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);`.
## Using Repository and the Model class
Each entity should have its Model class and Repository class if you are storing it in DB. Have a look at the demo application "blog-api": https://github.com/yiisoft/demo
In my case User model (file `src/Entity/User.php`) will only contain private attributes, setters and getters. UserRepository (placed in the same folder) may look like this to enable CRUD (compressed code):
```php
<?php
declare(strict_types=1);
namespace App\Entity;
use DateTimeImmutable;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidConfigException;
use Yiisoft\Db\Query\Query;
final class UserRepository
{
public const TABLE_NAME = 'user';
public function __construct(private readonly ConnectionInterface $db){}
public function findAll(array $orderBy = [], $asArray = false): array
{
$query = (new Query($this->db))->select('*')->from(self::TABLE_NAME)->orderBy($orderBy ?: ['created_at' => SORT_DESC]);
if ($asArray) {
return $query->all();
}
return array_map(
fn(array $row) => $this->hydrate($row),
$query->all()
);
}
public function findBy(string $attr, mixed $value): ?User
{
$row = (new Query($this->db))->select('*')->from(self::TABLE_NAME)->where([$attr => $value])->one();