Skip to content

Add dependency injection container to Drush. - #1884

Closed
greg-1-anderson wants to merge 16 commits into
masterfrom
drush-di
Closed

greg-1-anderson wants to merge 16 commits into
masterfrom
drush-di

Conversation

@greg-1-anderson

Copy link
Copy Markdown
Member

Motivation:

We'd like to be able to factor out key parts of Drush into libraries; key among these are the alias / backend invoke handling. We also want to move away from drush_get_context() for fetching important Drush service object references.

First step:

This PR initializes a DI container that has only the logger in it. This will allow us to also initialize Alias and Backend Invoke classes from an external library, and use DI to give them a logger.

Next steps:

We could use DI to construct all of the bootstrap objects. If some external plugin provided a bootstrap object, it could also initialize it with its own foo-services.yml, and make references to 'logger' et. al. as needed to construct its objects, since the DI container will already be initialized with all of the standard Drush instances. It would then need to make one more explicit call to add its bootstrap object to our bootstrap object manager.

We could use this technique for our bootstrap objects as well, so each DrushBootN had its own set of services, which instantiated the correct Rules8 vs Rules7 object, and gave them the same tag (e.g. 'rules'). This would make it way easier to provide platform-independent helper classes, or even use DI to provide the implementation for a group of Drush commands associated with a platform.

Comment thread composer.lock Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don think we upped our requirements to 5.5 yet. I'm fine doing so for Drush9. I'd be OK with this patch being our starting point for Drush9. No strong opinion.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Yes, this is definitely a Drush 9 feature. The biggest problem we have right now is that Drupal 8 has its own version of the Symfony DependencyInjection classes, which is causing the ContainerBuilder to blow[s] up due to some dependency hell problems. Since Drupal has its own copy, these incompatibilities can't be resolved simply by including Drush in the same composer.json as Drupal.

I'm still considering how to best solve this problem. It might be best if Drush also had its own DI container. It depends on exactly why the ContainerBuilder is failing; I haven't had the time to really look into this yet.

@weitzman

Copy link
Copy Markdown
Member

http://pimple.sensiolabs.org/ is a popular alternative. It looked nice and simple when I briefly looked a while back. I have no useful input beyond that.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I looked at the Drupal ContainerBuilder class, and it merely extends the symfony container builder; it does not replace it. It is possible that always using a site-local Drush would be a solution here. I might try setting up the Drush Drupal 8 tests to always use a site-local Drush.

Pimple looks fine if you want to initialize your DI in code. I saw that some folks use the Symfony YamlFileLoader with Pimple. That might be a solution; I have not looked into whether it would be an equivalent amount of revlocking as we already have with the existing ContainerBuilder. There is also td7650/yml2pimple, but it is a fork of an unmaintained project, and has no issue queue (the parent project has the issue queue). It also uses Pimple 1.x instead of Pimple 3.x, and an older yaml parser than we use.

Maybe I'll try the YamlFileLoader with Pimple, and see how far that gets us.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

The tests pass when Drush is using exactly the same version of symfony/dependency-injection as Drupal 8; perhaps this is sufficient, since we already use components that must be compatible with Drupal 8.

@weitzman

weitzman commented Dec 24, 2015 via email

Copy link
Copy Markdown
Member

@greg-1-anderson

Copy link
Copy Markdown
Member Author

We are already missing that feature--the global Drush can break against future versions of Drupal 8 at any time, and the current version of Drush doesn't work against older Drupal 8 betas and alphas. We don't notice the problem so much, because we happen to work with both 8.0.0 and 8.0.1, but this will be harder to do as time goes on, when there are more Drupal 8 versions using different sets of dependencies.

Still, I'll try out Pimple with the YamlFileLoader. If it worked out, it may delay the time until we run into problems.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I considered this a bit more, and I am a little reluctant to use pimple. It is similar to the Symfony dependency injection component, yet different; it seems undesirable and confusing to have different containers in Drush and Drupal.

I think it may be possible to make Drush slightly less vulnerable to some types of dependency hell, but it would take a little refactoring. If it does not work out, we can try switching to pimple later. For now, though, I think I'll continue from 64f617b, and refactore a small amount of Drush preflight logic into classes.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

My idea above was a dead-end; it was my thought that we could reduce some types of dependency hell by including the Drupal autoloader immediately after we included our autoloader, before we attempted to use any symfony classes. This could possibly work for drush --root=..., but in the case of drush @alias ..., we want to use DI to manage our logger and alias classes, so we would have to use symfony before we knew where the Drupal root is.

Fortunately, though, this whole problem seems to be a false alarm. I failed to check in composer.lock on one of my tests, leading to spurious failures that I thought was a dependency hell problem, but was actually simply an incompatible library versions problem.

Summary

  • We will still have problems if Drupal upgrades to symfony/dependency-injection 3.x, as, at that time, some versions of Drupal will be using 2.x (as it currently is), and we will have to pick one of 2.x or 3.x to use, and therefore will not support all versions of Drupal 8 with one version of Drush.
  • We already have this risk from other components we share with Drupal 8.
  • Using pimple will not significantly improve the situation, as we will still be revlocked to the YamlFileLoader. There are no good alternatives for this right now, as mentioned above, unless we want to maintain our own DI yaml loader.
  • Minor updates of symfony/dependency-injection are okay; so, we can use symfony/dependency-injection 2.7.7 while Drupal is using 2.7.6, and this does not cause a problem.

Given this, are we okay with moving forward with symfony/dependency-injection 2.7* in Drush 9?

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I'm starting to create a \Drush class modeled off of the \Drupal class from Drupal 8. This insulates the dependency injection code with static wrapper methods. If everyone uses these methods for any needed direct access to the DI container for legacy code, then we could switch to pimple later with minimal disruption, should it become necessary to do so.

I'll commit the code once it's ready, but I think it's safe to move forward with symfony/dependency-injection 2.7.* for now.

@weitzman

Copy link
Copy Markdown
Member

I'm generally +1 for this. I'll have a more considered opinion once the PR is more complete. Thanks for working on this.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I meant "add the code to this PR", not commit. Thanks for the interim feedback; will add more here when it is ready. I am also considering a non-DI version of the "Drush" class for Drush 7 & 8 to make it easier to backport code changes from Drush 9. Might be handy.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Here is the DI code using a \Drush class to manage the container, just as Drupal 8 does.

Next steps:

  • The various 'boot' objects, esp DrupalBoot8, could be created via dependency injection, and we could insert an instance of the logger into these instances via constructor injection. This would eliminate the call to \Drush::logger() in DrupalBoot8.
  • We could add an Alias service class, and use that for loading and resolving alias files.
  • We could create a wrapper object for Drush backend invoke.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Another thing to consider is how to handle Drush version. In Drupal, this is just \Drupal::VERSION, which has the advantage of being able to be accessed easily after including the autoload file. In the current implementation of this PR, though, this is not implemented, because the current version of Drush stores the version number in a "drush.info" file that could potentially be read by some other tool or process. PHP constants cannot be initialized with code; as the name implies, they must be initialized with a constant. We therefore use a slightly different implementation that can still read the drush_info file for backwards compatibility. If there are no external programs that read this file, we could consider just using a \Drush::VERSION constant, like Drupal 8 does.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I moved our global includes into the autoloader, because that is where they belong.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I am going to back out 6c84c76. Placing all of our global includes in the autoloader is very convenient and useful, but there are two problems with it:

  1. All of the Drush global includes would be parsed by Drupal on every request, even though they were not needed.
  2. It would make it perhaps even too convenient to have all of the legacy global functions available at all times, which could potentially slow down our efforts to migrate these to lazy-loadable classes.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

This PR adds dependency injection for the bootstrap objects; some additional code cleanup still needed, but the basic structure is in place.

Note that this PR also removes the mechanism that Backdrop is using to hook into Drush to provide its own bootstrap object. To bring that back, we would need to implement a compiler pass to find and add bootstrap extensions.

We should decide on coding conventions to use here. For functions I moved over from bootstrap.inc, I retained underscore_naming, but these should probably all be converted to camelCase.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Another good thing to do here would be to move all of bootstrap.inc into the BootstrapManager class; however, there are references in bootstrap.inc to both site alias and backend invoke code; any such references in the Drush\Boot classes should also be done via dependency injection. I'm not sure if these code paths should even exist here; I'll probably work on separating out site aliases before refactoring any more functions in bootstrap.inc. I think we could just remove the word "DRUPAL" from the bootstrap levels, though, and make these standard for use by all frameworks, since the concepts are general enough. I think that the drush_bootstrap_value() function could be removed, though, and other storage could be used instead here. In general, I think it is a good strategy to remove any use of drush_set_context() that is used for global variable storage rather than context (option) storage.

Note that Drush-specific code can use custom log levels, like LogLevel::BOOTSTRAP, but any set of classes that might be separated out into a standalone library should only use the standard PSR log levels. I think that the bootstrap log level is still useful enough to keep around.

Comment thread lib/Drush.php Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there two examples here? I don't get the Lock example

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut-copy-pasta error! I based my comment on the advice given in Drupal 8, edited it for Drush, and did not remove that part. It should not be there.

Comment thread lib/Drush.php Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's leave this info in the .info file for now.

@weitzman

Copy link
Copy Markdown
Member

I'm traveling so can only give brief comments.

this looks terrific. KEEP GOING!

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I will keep going here. I kept getting blocked on other attempts to refactor for various reasons; I think this will break the log-jam, and allow us to move forward in a number of areas we have wanted to improve for a long time.

…he BootstrapManager; update legacy calls to same.
… them 'bootstrap.boot', so that additional boot objects may be added in extension service files (when we support that).
@greg-1-anderson

Copy link
Copy Markdown
Member Author

Now we use a compiler pass to identify tagged services, so we could potentially add more 'boot' classes simply by loading more service files (e.g. a Backdrop Drush service file, found at the document root, or maybe docroot/drush).

@greg-1-anderson

Copy link
Copy Markdown
Member Author

So, it is kind of a problem that we cannot alter the container after it has been compiled. Re-initializing the container like this is undesirable both in terms of performance and behavior, as you risk dumping dynamic parameters, if we end up using that feature. Even if we do not use that feature, it feels wrong to throw out the container and re-initialize it multiple times.

I think we need to do something more like this:

  • Initialize the container and load our services
  • Preflight far enough to identify the site root. Load additional services defined by the framework.
  • Ask for all of the services tagged 'bootstrap.boot'
  • Manually add those services to the Bootstrap manager
  • Bootstrap far enough to identify modules (this pretty much means a full bootstrap for the command)
  • Add services / commands defined by the modules via the Symfony extension mechanism
  • Compile the container

The thing that is dissatisfying about this is that parent services and potentially others--and certainly any compiler passes--cannot be used until the container is compiled.

I am unsure whether or not it is important to use parent services (a simple optimization) or compiler passes. I sort of presumed that the reason Symfony has a compiler pass feature is to allow objects to be fully initialized before they are given to any other object (e.g. via constructor or setter injection). However, it seems that dependency injection happens at load time, and compiler passes happen at compile time. If this is in fact the case, then perhaps the proposal above is sufficient.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Drupal 8 modules can define their own services (scroll down). These are part of the Drupal 8 container rather than the Drush container. We could use the Drupal 8 container to find tagged classes that are Drush extensions, just as we find tagged Boot classes in this PR. Doing this would be compelling insofar as we would not need to spend any effort on the container, or finding modules, as Drupal has already done that for us. The down-side of this approach, though, is that the dependency injection done in the module's services file could only reference Drupal services; the Drush services would all be invisible.

The alternative would be for us to load our own example.drush-services.yml file (for the "example" module), in which case it would be possible to use DI to inject Drush services into the module's cli classes. However, this alternative has the inverse problem, which is to say that the module's cli classes then could not use DI to reference the services defined in Drupal. This might be even more disadvantageous, as the purpose for writing a Drush extension in a module is to make it easy to call the Module / Drupal code.

I am not sure whether we might be able to just merge the two containers together somehow; that would be cool, but might not be possible.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Combining the two containers together is pointless; this presumes that you'd have both Drush and Drupal services in the same module services.yml file, which would blow up when it was loaded by Drupal w/out Drush.

We'll have to find our own drush-services.yml file in each module, and load it separately if it exists. The module's Drush extension will then need to use \Drupal::service() to obtain objects constructed via Drupal's DI loader.

Comment thread includes/preflight.inc

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use the @deprecated annotation on things like this,. That way PHPStorm lets you know that you are being naughty.

@weitzman

weitzman commented Jan 7, 2016

Copy link
Copy Markdown
Member

This looks terrific. When you are satisfied, feel free to create 8.x branch and then merge this into master.

A few non-urgent questions:

  1. Where do Drush properties living like DRUSH_VENDOR_PATH, DRUSH_COMMAND, etc.
  2. Where should we do validation like minimum PHP check, is_cli() check, etc.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

I hope to provide a configuration class to replace our context system. Ideally, new commands will gain access to drush_get_option() and drush_get_context() via an object that they may obtain via dependency injection. Still working out how this should best work; ideally, all of the "work" should be done by library functions (classes) that can be called with parameters instead of global state.

I could potentially commit here before solving that problem; I want to take one more go at determining our container strategy first. We can always adjust the implementation later if I don't get it exactly right the first time.

@greg-1-anderson

Copy link
Copy Markdown
Member Author

Continued at #2018

@greg-1-anderson
greg-1-anderson deleted the drush-di branch March 9, 2016 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants