@@ -154,6 +154,96 @@ return [
154154For local installation without Docker the host in Dsn would be `localhost`. You'll have to adjust the rest to match
155155how you configured the database.
156156
157+ # ## Multiple database connections
158+
159+ When the application works with several databases, keep `ConnectionInterface` for the primary connection and add a
160+ class alias for each named connection :
161+
162+ ` ` ` php
163+ <?php
164+
165+ use App\D b\A nalyticsDatabase;
166+ use App\D b\M ainDatabase;
167+ use Yiisoft\D b\C onnection\C onnectionInterface;
168+ use Yiisoft\D b\P gsql\C onnection;
169+ use Yiisoft\D b\P gsql\D river;
170+
171+ /** @var array $params */
172+
173+ class_alias(Connection::class, MainDatabase::class);
174+ class_alias(Connection::class, AnalyticsDatabase::class);
175+
176+ return [
177+ ConnectionInterface::class => MainDatabase::class,
178+
179+ MainDatabase::class => [
180+ 'class' => Connection::class,
181+ '__construct()' => [
182+ 'driver' => new Driver(
183+ $params['app/db']['main']['dsn'],
184+ $params['app/db']['main']['username'],
185+ $params['app/db']['main']['password'],
186+ ),
187+ ],
188+ ],
189+
190+ AnalyticsDatabase::class => [
191+ 'class' => Connection::class,
192+ '__construct()' => [
193+ 'driver' => new Driver(
194+ $params['app/db']['analytics']['dsn'],
195+ $params['app/db']['analytics']['username'],
196+ $params['app/db']['analytics']['password'],
197+ ),
198+ ],
199+ ],
200+ ];
201+ ` ` `
202+
203+ The alias class names are used as service IDs and type hints. They don't need PHP files of their own.
204+
205+ Define matching parameters :
206+
207+ ` ` ` php
208+ use Yiisoft\D b\P gsql\D sn;
209+
210+ return [
211+ // ...
212+ 'app/db' => [
213+ 'main' => [
214+ 'dsn' => new Dsn('pgsql', 'db', 'app', '5432'),
215+ 'username' => 'user',
216+ 'password' => 'password',
217+ ],
218+ 'analytics' => [
219+ 'dsn' => new Dsn('pgsql', 'analytics-db', 'analytics', '5432'),
220+ 'username' => 'analytics_user',
221+ 'password' => 'analytics_password',
222+ ],
223+ ],
224+ ];
225+ ` ` `
226+
227+ Services that need the primary database can still depend on `ConnectionInterface`. Services that need another database
228+ should type-hint the corresponding alias :
229+
230+ ` ` ` php
231+ <?php
232+
233+ declare(strict_types=1);
234+
235+ namespace App\R eport;
236+
237+ use App\D b\A nalyticsDatabase;
238+
239+ final readonly class ReportRepository
240+ {
241+ public function __construct(
242+ private AnalyticsDatabase $connection,
243+ ) {}
244+ }
245+ ` ` `
246+
157247# # Creating and applying migrations
158248
159249For the initial state of the application and for further database changes, it is a good idea to use migrations.
0 commit comments