Skip to content

Autoload-based automatic registration of service dependencies #282

@jtojnar

Description

@jtojnar

If I want to have some class usable for auto-wiring, it needs to be registered in the container, otherwise auto-wiring will throw a MissingServiceException – I assume this is to prevent accidentally trying to create a random object in the container, which could hide that a class actually needs the object instantiated in a different way.

Currently, my options are either:

The latter is based on RobotLoader, which, in addition to repeating the work already done by Composer in most modern projects, can cause issues when some of the classes are not loadable.

For instance, barista is a Nette-based tool and it currently uses the search extension to locate services in the src/ directory. But the src/ directory also contains some helper classes, including one that depends on PHPUnit – even though the tool itself does not depend on PHPUnit so it might not be installed. When that is indeed the case, the search extension causes it to be loaded by calling class_exists, crashing the autoloader due to a missing PHPUnit class in the process.

Since this app is not actually needed in the first place and is only attempted to be registered due to it being in the src/ directory, I propose adding another extension for automatic registration of dependencies in addition to search that, instead of a directory, would look at the dependencies of explicitly registered services and try to register them, if they are not registered already. The interface could look something like the following:

autoloaderRegistration:
    # Registers any dependency required by services that is in the Barista namespace:
    namespace: 'Barista\\'
    excludes:
      - 'Barista\\Testing\\'

Would that be possible to implement? My main worry would be that the container also supports runtime auto-wiring of classes that are not registered. Dependency trees of those would not be available to the compiler. But that does not seem to be the case if I am looking at DI\Autowiring correctly. And even if it were, we could just have ignored those.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions