Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
Repo info
Bram Van der Sype
It happened in the upgrade from php-di 6.1 to 6.2, I'm guessing it has something to do with the change of the closure thingy
Adam Bosco

Hey all! I'm wondering if I can look up a key within a get()'d array in a autowire()->constructorParameter() somehow. This was my first stab, and I understand it doesn't work because get() is a definition helper, not an immediate lookup:

return [
  'config' => [
    'foo' => 'bar'

  'my.object' => autowire( MyClass::class )
    ->constructorParameter( 'foo', get( 'config' )[ 'foo' ] )

I understand that I could do this with a factory function, but I'm really curious as to if there is a way to do so without one?

How do I use PHP-DI in codeigniter 4
Hi, a query, how can I make a library I have generated, auto-inject into the application that uses it. Is this possible?

I tried something like this:

class CacheServiceProvider implements ServiceProviderInterface

 * @param Container $pimple
public function register(Container $pimple): void
    $pimple[CacheAdapter::class] = [self::class, 'getCache'];
But doesn't work!
Maciej Fikus

Hey guys, I've quick question as I do not understand it from docs.

How does @Inject work? It is said, that I can use it while I do not have control over object creation (i.e. some package).
The Object is created "by hand" somewhere (new Object(itsparams)) - then, I would like to inject some properties from container

I mean, it can't be used in this way, right? It can be used only if object itself is controllered by container?
are you here?
Mohamed Cherif Bouchelaghem
Seems that factory function doens’t accept callable like:
class MyServiceFactory {
   public function __invoke(ContainerInterface $container)
        //creation logic here!
The issue is when compilation is enabled, without compilation everything work fine
Anyone faces this issue before?
to workaround this:
     return (new MyServiceFactory)->__invoke($container);
Hans-Helge Buerger
Hey there, is there a way in PHP-DI to return always a new instance of a class. factory() returns always the same instance, but I need a new instance for every injection.
Anaël Ollier
Hi @obstschale In my understanding of the documentation and the current state of the library, you need to create a factory class yourself for this kind of need, and use something like Container->make(...) in order to force creating a new instance of your class.
Hans-Helge Buerger
Ok. Thx for your help
Hello everybody. I have questions about other files (css/js).
How I connect personal css file ? Thank you.
Mohamed Cherif Bouchelaghem
Hi, how you guys organize dependencies without being a mess?
Split to bunch of arrays and merge them?
Maybe the question was asked before, I just would like to know if there is any pattern to follow?
Anaël Ollier

Hi @cherifGsoul There's no pattern, at least none that I know of. I personnally split the directives in 4 files, based on the "type" of them.

return array_merge(
    include 'sections/10-values.php',
    include 'sections/20-preferences.php',
    include 'sections/30-definitions.php',
    include 'sections/40-virtual.php'

Where "preferences", "definitions" and "virtual" are derived from what you can find in Magento 2 (just because I'm used to it).

  • values: keys are simple strings, often reused later, ex: 'app.base_url' => "some_value"
  • preferences: keys are interface names and define a preference for a given interface, ex: \App\BootstrapInterface::class => \DI\get(\App\Bootstrap::class)
  • definitions: keys are class names and define dependencies, ex: \App\Bootstrap::class => \DI\autowire()->constructorParameter(...)
  • virtual: keys are virtual class names and also define dependencies, ex: 'App\ApiBootstrap::class => \DI\autowire(\App\Bootstrap::class)->constructorParameter(...)
    So far, it covers all my cases :)
Mohamed Cherif Bouchelaghem
@nanawel thanks you for sharing your approach, I really like it and give me ideas
Anaël Ollier
There's a mistake in the last line, the example should be 'App\ApiBootstrap' => \DI\autowire(\App\Bootstrap::class)->constructorParameter(...) (the key should be string, not a ::class)
Mohamed Cherif Bouchelaghem
@nanawel Yeah I got it since is virtual
Anaël Ollier
Mohamed Cherif Bouchelaghem
Plus this page in the docs https://php-di.org/doc/definition-overriding.html gives some insights about organizing big applications definitions.
Callum Hopkins
hi all, anyone know where i can find some documentation about using mocked service in PHPUnit with PHP-DI? we are using the annotations to inject services into our classes and need to be able to inject a mocked version of the service when running out PHPUnit tests
Hello, is there a way to get the class name that required specific dependency?
What I try to do, is that when I use Doctrine ORM, I want to use generic repository classes that are retrieved using EntityManager::getRepository("EntityName"). But I don't want to pass EntityManager itself only to get generic repository out of it so I was thinking if I just could typehint to generic EntityRepository class and somehow pass in the required "EntityName"
So I could in my service just typehint to generic EntityManager and get the requiring service class name and the name of the entity from that, e.g. UserService => UserEntity => UserRepository
Or should I just manually configure all my services?
Lewis Cowles
Are there any plans for PHP-DI to offer addSingleton or addTrait, a bit like .NET DI? Is there a nice singleton proxy people recommend using to be able to ensure the single-ness of a particular dependency?
Lewis Cowles

I Also do not understand https://php-di.org/doc/definition-overriding.html#decorators chronology. Are the two snippets from different files?

I'd have thought having the same array key, that the definitions would overwrite. I think this might be why they are shown as they are, separate arrays, but something to confirm this would be nice.

For example, could I use this syntax with add if singular? or is addDefinitions the only way this works?

Anaël Ollier
@Lewiscowles1986 To me it's 2 distinct, subsequent calls to addDefinitions(), otherwise of course the second key of the array overwrites the first one.
ShaoBo Wan(無尘)
Jean-Luc Herren
Hi everyone! In the PhpDoc of ContainerBuilder::enableCompilation() it says for the parameter $containerClass: "Name of the compiled class. Customize only if necessary". Is there any downside in deviating from the default class name, or why does it say to only do that if necessary? The reason is that I would like to have two different containers, which obviously will need to compile to two different filenames.
Navarr Barnier

Hi, I'm having some issues and I'm not sure what I'm doing wrong.

I've got a class "DeclaredDependencyAggregator" which depends on an interface. That interface is registered in the definitions with an implementation. The implementation has dependencies. DI is failing to find the implementation dependencies through auto-wiring, which are also registered.

Here's a lean version of the container build:

$containerBuilder = new ContainerBuilder();
        Composer::class => $this->getComposer(true),
        ComposerScopeDeterminer::class => create(ComposerScopeDeterminer::class)
            ->property('scope', $composerScope),
        ScopeDeterminerInterface::class => create(ComposerScopeDeterminer::class),
$container = $containerBuilder->build();

Here's a lean version of the error message:

  Entry "Navarr\Depends\Command\WhyBlockCommand" cannot be resolved: Entry "Navarr\Depends\DeclaredDependencyAggregator" cannot be resolved: Entry "Navarr\Depends\ScopeDeterminer\ScopeDeterminerInterface" cannot be resolved: Parameter $composer of __construct() has no value defined or guessable  
  Full definition:                                                                                                                                                                                                                                                                                       
  Object (                                                                                                                                                                                                                                                                                               
      class = Navarr\Depends\ScopeDeterminer\ComposerScopeDeterminer                                                                                                                                                                                                                                     
      lazy = false                                                                                                                                                                                                                                                                                       

Here's what ComposerScopeDeterminer's constructor looks like:

public function __construct(
    Composer $composer,
    PhpFileDeterminer $phpFileDeterminer,
    #[ExpectedValues(valuesFromClass: ComposerScopeDeterminer::class)]
    int $scope = self::SCOPE_PROJECT_ONLY
) {

EDIT: Wherever I was using create I should've been using autowire. I clicked an earlier link, seemingly unrelated, saw the syntax, and decided to try that.

Andrew Vehlies

Hi, I'm coming from a Java/Spring background. There was a super useful feature in Spring that would let you autowire/inject all implementing classes of an interface like this https://www.baeldung.com/spring-injecting-collections#reference

I was hoping to find some way in PHP-DI to do the same thing. Was planning on using this in an AMQP Message Router. Have some MessageHandler interface which has a canHandle(string) method and the message router would basically loop through all of those and see if a certain message type could be handled. I was hoping to avoid having to autowire each individual implementation. Any idea on how I could do something like this, or am I just trying to do something that really isn't in the wheelhouse of PHP-DI?

Andrew Vehlies
I suppose something might be able to be done with "autoload": { "files": "some/dir/of/handlers" } in composer.json and then loop through get_declared_classes() and check if they implement?
Andrew Vehlies
turns out that's not the case since composer's classmap autoload won't list a class in get_declared_classes() until it's actually requested
Mario P
Does PHP-DI support similar functionality to Symfony service tagging?
Currently, what I am doing to replicate tagging is via arrays defined in the DI container
Mario P
'my-tag-1' => [get(Service1), get(Service2)]
Anaël Ollier
@mario-p_gitlab Not to my knowledge. That would be handy though.
Mario P
I was thinking of adding 2 new features,
Service::class => autowire()->tag('tag-1')
SomeOtherService::class => autowire()->constructorParameter('some-collection', getByTag('tag-1'))
Andrei Dascalu
Hi everyone, wondering if there's anyone around
Is it possible to use @Inject annotation to extra a value from an array? (eg, I have 'config' => ['item' => 1, 'test' => 2 ] and I would like to inject config['item'] on a private class member)
Can anybody help me with this error: Too few arguments to function App\Model\DbObject::__construct(), 0 passed in C:\laragon\www\newswebsite\src\Model\DbObject.php
Aguirre, Lautaro Wenceslao
Hi. Does PHP-DI support PHP Attributes for doctrine?