-
-
Notifications
You must be signed in to change notification settings - Fork 72
Description
Hello,
quite often I need to deal with the order of extensions when compiling and it would be very useful if DI could do this automatically. Because this problem bothers me a lot, I immediately came up with it and tested a fully functional and stable solution several times.
Extension behavior design
What extensions must be registered before or after my extension is usually best known to the developer of the particular package himself, so we could add the mustBeDefinedBefore()
and mustBeDefinedAfter()
methods to the CompilerExtension
class. Both methods will return an array of strings (the content of the string is the class-name of another extension, on which we create a dependency on the order).
Examples of uses in a particular extension are:
final class CmsExtension extends CompilerExtension
{
/**
* @return string[]
*/
public static function mustBeDefinedBefore(): array
{
return [OrmAnnotationsExtension::class];
}
Order processing
All available extensions are stored in the Nette\DI\Compiler
service in the $extensions
property. Before reading this field in any way, a sort method should be called that returns a list of extensions in order to preserve the correctly set dependencies.
I understand that the sorting algorithm can be complicated if all dependencies are to be preserved. As part of saving work, I therefore prepared it and have been using it on all projects for some time.
The algorithm does not guarantee a stable sort order, but always sorts the services to guarantee the required conditions.
Algorithm example: https://github.com/baraja-core/package-manager/blob/master/src/ExtensionSorter.php
Thanks!