2

Getting my head wrapped around dependency injection with php-di, but I'm obviously not doing something right. Wondering if someone could tell me what I'm doing wrong.

Ok, have a bootstrap.php file, no namespace in it, and looks something like:

`<?php

use myapp\app;
use myapp\interfaces\db;
use Psr\Log\LoggerInterface;
use myapp\lib\log;
/// A bunch more 'use' statements here ///


// Start app.  The myapp\loader() class extends DI\Container, hence is also the HTTP container.
$app = new myapp\loader();

// Set classes
$app->set(app::class, $app);
$app->set(loggerInterface::class, $app->make(log::class, ['channel_name' => 'some_changeable_name']));
$app->set(db::class, $app->make(myapp\lib\mysql::class));

// Return
return $app;

I'm sure you can at least see what I'm trying to do, and it does technically work, although I'm sure I'm doing it wrong.

I want it to be interchangeable, so for example, you can easily flip out the internet logger for the monolog/monolog package, or change the default log channel name, or flip the database driver to some class other than mysql, etc.

However, these classes depend on each other, hence have to be set in this order, and if placed within ContainerBuilder->AddDefinitions() method, it just throws an error saying the app::class can not be resolved. For example, the log::class constructor has the 'app:class' injected into it, the constructor for db::class has both app::class and loggerInterface::class injected, etc. Plus, I need to be able to put name based parameters in when defining these.

Any insight would be helpful, as I highly doubt this is the best way to go about it, even though it does work. Am I supposed to inject only the container into each of these callses, then grab the necessary objects / classes via the "container->get()" method? It would be much nicer and easier to read if I could just inject directly into the constructor though.

Any help / insight would be greatly appreciated.

Envrin
  • 19
  • 1

0 Answers0