Problem/Motivation
#3442009: OOP hooks using attributes and event dispatcher is in, and it's possible now to move hooks to services. But only in modules at the moment.
To make system module smaller, specifically and possibly also further on make more things components it would be very valuable to make components more self-contained.
#3383487: Add CronSubscriberInterface so that services can execute cron tasks directly and specifically system_cron() is a good example. It calls out to several components like caching, flood, key value. While the #Hook attribute is still a dependency on Drupal or at least another component, it would allow us to move code together.
Proposed resolution
Approach presented in MR 15722:
- The only API to alter (meaning reorder or remove) Hook implementations is to use the order properties (with OrderAfter/Before, etc) and the ReOrder and RemoveHooks
- Hook implementations will always run in the class they are defined in: If services that have hooks are decorated or altered to be other classes, hooks will still run in the original class, and no hooks defined in the replacement classes will run
- This is implemented by excluding service definitions that decorate other services from hook discovery. And there is validation in HookCollectorKeyValueWritePass to confirm that hook services have not had their class changed
- Also, HookCollectorPass runs before the service provider pass, so dynamic services provided by service providers are excluded from hook discovery
- If a registered service has hook implementations, then another service is registered with ID "hook.{FCQN of service}". This allows service decorators and or service modifiers to change the original service definition without affecting the registered hooks. For event subscribers that have hook implementations, the second service definition has autoconfiguration set to false so that the event listener is not registered multiple times
- Services can be defined in the Core namespace
- Services that are abstract, synthetic, made from a factory, or deprecated are skipped from hook discovery. (May be worth discussion about whether deprecated services should be skipped, but it's done in the MR to prevent warnings from being triggered every time a module with a deprecated service is installed.)
Remaining tasks
Some decisions about the behavior of service definitions that are altered by service decorators or module ServiceProviders should probably be made first before proceeding, otherwise it will be more complicated dealing with it later:
For services altered by service decorators, assuming original Service1 is decorated by Service2 and Service3, with Service3 being the outermost, Service2 in the middle, and Service1 being the innermost:
If there are #[Hook] methods in every class, should:
Only Service1's hook methods be invoked?Only Service3's hook methods be invoked?All three classes' hook methods be invoked?Any service with Hook attributes not be allowed to be decorated?
For any service (e.g., with class Service1) altered by a module service provider (e.g. class Service2), should
Only Service1's hook methods be invoked?Only Service2's hook methods be invoked?Both classes' hook methods be invoked?Any service with Hook attributes not be allowed to be altered?
Then for RemoveHook, OrderBefore, OrderAfter, currently these attributes target classes + methods.
Should these be changed to target service ID (which could be a class name, but the target would be the resolved service object) + method?If so, do these parameters need to deprecated and replaced with renamed ($class->$service,$classesAndMethods->$servicesAndMethods) ones?
Alternative
One of the stated goals in the description is to reduce the size of of the system module. This can still be done by rescoping this issue (or opening a separate one and doing that first) to add a directory Drupal\Core namespace where hooks can be discovered. This probably doesn't help componentize though, since likely this just means the system module hook classes get moved into the core namespace.
User interface changes
API changes
Data model changes
Release notes snippet
| Comment | File | Size | Author |
|---|
Issue fork drupal-3481903
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #2
geek-merlinYes, this would help a lot. Also, the restriction to the
Hooksnamespace is problematic even in modules:I implemented hundreds of hooks in the hux POC, where there was the choice to use either the Hooks namespace with auto-service registration, or ANY service. In >90% of the cases, from a code organization perspective, the hook was best to live where it belonged semantically, not in the Hooks namespace.
Or stated it differently: For sane code organization, restrikting hooks to Drupal\my_module\Hooks is the same PITA as to have to put them in the module file.
Comment #3
rodrigoaguileraWhile migrating a module to OOP hooks I noticed that the restriction of "one implementation per module" is still there. Now is rather silent as there is no error about it. For example having two classes in the \Drupal\my_module\Hook namespace that have the same hook annotations.
I would be really convenient to have multiple implementations per module to organize related features into the same class. E.g. a module that has two field widget third party settings and each one has its hook_field_widget_third_party_settings_form with a corresponding hook_field_widget_complete_form_alter. One implementation for each of the third party setting separated in different classes.
Is this something that can be tackled in this issue or should I open a new one?
Comment #4
nicxvan commentedYeah we need to update that cr. The one per module restriction was added back when we had to fix hook module implements alter.
Comment #5
nicxvan commentedHowever you can still mark one method with more than one hook.
Comment #6
rodrigoaguileraCan you link to the issue? Just want to investigate if there is a possibility to be added back.
I updated the CR to clarify the point about the multiple implementations
https://www.drupal.org/node/3442349
Comment #7
nicxvan commentedhttps://www.drupal.org/project/drupal/issues/3484754
Comment #8
nicxvan commentedThank you, it can be added back once we remove hmia. But we can't reorder between.
Did your module not even pick up the multiple? Imd acrylamide like to see the example. Can you share the code?
Comment #9
rodrigoaguileraThanks for the link.
The project I migrated is https://git.drupalcode.org/project/change_labels/-/tree/1.x?ref_type=heads
but is already frankensteined with traits to workaround this issue that I'm talking about.
To showcase the problem I created a patch for automated_cron with similar hook_field_widget_third_party_settings_form implementations.
Only the "second" implementation end up displaying its form in the widget settings.
Maybe this is a special case since the calling module is important to later determine where to save the third party setting.
Moving one of the classes to another module (and changing the namespace) makes both form items to appear.
Comment #10
godotislate@rodrigoaguilera My understanding is that having multiple implementations of the same hook in a module makes re-ordering hooks via
hook_module_implements_alter()convoluted, so there will be only 1 hook per module allowed until the whole procedural hook BC layer is removed in the future.As for this issue: I think the need can be addressed by something similar to WIP MRs in #3376163: Support #[AsEventListener] attribute on classes and methods. If we do the following, then registered services that have the #[Hook] and #[AsEventListener] attributes should get registered correctly as event listeners.
Hookattribute a subclass ofAsEventListenerThere is the risk that someone registers a Hook service in their .services.yml, and the class for the service is in the Hook namespace, that the listener would get added twice and fire twice per event, but it can be documented that services in the Hook namespace should not be added to services.yml, and services outside that namespace should.
Comment #11
ghost of drupal pastThe hmia patch did not remove the multiple implementations feature.
The problem is in
EditFormDisplayEditForm::thirdPartySettingsFormas it stores the return value of $hook into $settings_form[$module].As for supporting the hook attribute in any service, that's not a particularly hard problem, it's just a performance/memory nightmare as you'd need to reflect every class and method defining a service to see whether they have a #Hook attribute. Of course, it's not my call but if it were then I'd split Rodrigo's problem into a separate issue and postpone this one on #3486503: Add a persistent cache for file-based discovery based on FileCache at least. But it's possible #3395260: Investigate possibilities to parse attributes without reflection would be needed. Just a suggestion.
Comment #12
godotislateYeah, forgot to mention that the MRs for #3376163: Support #[AsEventListener] attribute on classes and methods need to be rebased, but I was holding off on that until #3478621: Add filecache to OOP hook attribute parsing goes in.
Comment #13
rodrigoaguileraApologies for the noise. Indeed multiple implementations are supported but there is special cases like hook_field_widget_third_party_settings_form that won't work the multiple implementations. Will file an issue for that.
I changed the CR to reflect that
https://www.drupal.org/node/3442349
Comment #14
ghost of drupal pastIndeed let's move to a separate issue, the fix is as simple as
$settings_form[$module] = ($settings_form[$module] ?? []) + $hook(that a trivial bug / missing feature it's not worth changing main CR over a small bug. Like, of all hooks only field_widget_third_party_settings_form/field_formatter_third_party_settings_form is affected and it won't be affected for long.Comment #15
rodrigoaguileraFiled #3489707: Support multiple implementations for hook_field_widget_third_party_settings_form and field_formatter_third_party_settings_form in the same module
Comment #16
berdirFor example \Drupal\Core\Extension\ModuleHandler::invoke() does in fact only support a single hook for a given module, I assumed that's true in general, and based on that adjusted ultimate_cron in #3489356: Support #Hook cron implementations to still check for hooks and invoke them through the module handler. Might need to change that then, but the nice thing about this approach is that it doesn't care about where that hook lives exactly, same config works in D10 and D11.1+.
Back to the topic.
> As for supporting the hook attribute in any service, that's not a particularly hard problem, it's just a performance/memory nightmare as you'd need to reflect every class and method defining a service to see whether they have a #Hook attribute
Two ideas to make that less of a nightmare.
a) What if we'd make the discovery/reflection opt in? We do it for everything in the Hooks namespace, but if you explicitly add a tag to your service, we scan that too? Means autoconfig of services won't work.
b) We keep the Hook namespace restriction, but expand it to components. That only helps core (for now?), but it's similar to plugin discovery, where we support that too (various plugins are for example in (Drupal\Core\Entity\Plugin). So if we want to move the cache component part of system_cron() to the Cache component, we'd add a Drupal\Core\Cache\Hooks\CacheHooks class?
Comment #17
ghost of drupal pastHrmmmm, I will update the CR to talk about
::invokethe original IS did it just didn't make it into the CR -- in short, those are an anomaly too, those are not really hooks :) and luckily there are very few of them. Edit: added "Also, a module can implement almost all hooks multiple times as documented on theHookattribute itself."To be on topic. Sure, adding a service tag to indicate it's a hook and then adding those classes into
HookCollectorPassis certainly a possibility. Let's think aloud what that would take, first it needs an optional$containerpassed tocollectAllHookImplementations(optional becauseModuleHandler::addcalls it). Once that's there code should read something like:That's nice -- but there's no
$module. That information just doesn't exist and while for service YAMLs it could be persisted with a little effort --DrupalKerneldoes index$this->serviceYamlsby$moduleeven if it doesn't pass it on -- services created by providers do not have this information.I am guessing you could make
$moduleoptional inaddFromAttributeand grab the module from the class name:this will work for Drupal modules and when it doesn't, well, just specify
$modulein#[Hook]. Most of the time it is irrelevant anyways --invokeAllWithneeds it because it calls$callback($listener, $module);where$moduleis cheerfully ignored ininvokeAlland indeed in almost all code usinginvokeAllWithbut still, that signature can't be changed without serious upheaval and so something needs to be supplied there.Someone else will need to turn this comment into PR.
Comment #18
geek-merlin@ghost of drupal past #11, @berdir #16, et al
Maybe you are not aware of
$container->registerAttributeForAutoconfiguration?See #10 on how to implement.
Comment #19
geek-merlinComment #20
godotislateThe
$container->registerAttributeForAutoconfigurationis directly copied from Symfony Framework bundle: https://github.com/symfony/symfony/blob/e128d76b3dfd5147fe1263a807e8ce83..., but it effectively just does the reflection looping that is the performance issue in question.Comment #21
geek-merlin> but it effectively just does the reflection looping that is the performance issue in question.
Which means:
- That compiler pass is already in place, iterating over all services, and no nightmare happened.
- It's the central place to do the reflection, with no performance penelty for any additional consumer.
So IF
$container->registerAttributeForAutoconfigurationis used, i see no rational reason for performance fear left.Comment #22
godotislateIt only iterates with reflection if attributes are registered for autoconfiguration via
$container->registerAttributeForAutoconfiguration. Right now there aren't any in Drupal core, so this reflection iteration does not occur.Comment #23
ghost of drupal pastSupporting magic naming instead of or in addition to tagged services is a good idea, thanks. But I don't think it merits a separate issue, indeed it should be discussed here:
Implementations wise, this is once again a minor tweak to HookCollectorPass. In this case, the filter iterator needs a minor adjustment: the iterator should iterate all of src instead of src/Hook but only return php files if the subPath starts with Hook or the file name ends in Hooks. This is not a problem, much as it was trivial to support tagged services the same is true for magic named classes.
As noted above, the problem is how every class reflected by PHP stays in memory until the end of the request regardless whether Symfony or Drupal does the reflection. There's work being done elsewhere to utilize crafty caching and/or nikic/php-parser to avoid the massive memory hit. Both magic naming and tagging would make an initial process faster but ultimately might not be necessary if these efforts bore fruit.
This memory hit is new. Up until now only plugins started using attributes but from 11.1 all hook implementations will become OOP.
So really the decision is
Ps.: registerAttributeForAutoconfiguration is only used by the full Symfony framework, not the components as shipped and I am fairly sure it requires the Symfony Config component.
Comment #24
geek-merlin> registerAttributeForAutoconfiguration is only used by the full Symfony framework, not the components as shipped and I am fairly sure it requires the Symfony Config component.
Hmm, i am using it i a quite big customer project with >300 contrib and custom modules to autoregister hux classes. No package added, except ~10 lines of custom code, and no extraordinary container build times.
Comment #25
alexpottI created a duplicate of this (which I closed) - #3502472: Allow any service to subscribe to hooks which lists some more reasons to do this:
We have a lovely new hooks system that integrates the module handler and the event dispatcher to invoke hooks. In doing this we had to move a hook. core_field_views_data to \Drupal\views\Hook\ViewsViewsHooks::fieldViewsData() even though what it does - provide entity reference field integration with views could be considered to be core's responsibility.
Another example could be kernel tests to enable hook testing whether the test and the test hook implementation live side-by-side - see #3502432: Make hook testing with kernel tests very simple
Also this could be used to make things like
from \Drupal\workspaces\Hook\WorkspacesHooks simpler. \Drupal\workspaces\WorkspaceManager::purgeDeletedWorkspacesBatch could subscribe to the hook - although we'd have to ensure anything that decorates it is also subscribed...
Comment #26
godotislateSo while core does not use
$container->registerAttributeForAutoconfiguration, withand several interfaces registered for autoconfiguraiotn in
CoreServiceProvider::register()with$container->registerForAutoconfiguration()(noAttribute), it does turn out that at compile time all core services are iterated over and reflected.Given this, @ghost of drupal past mentioned that all service classes are being loaded into memory at compile time anyway, so iterating with reflection on these classes to discover class-level `Hook` attributes has a negligible affect performance. @nicxvan also ran performance tests iterating reflection through each of a class's methods, and the hit on performance was not significant even with the number of methods in the class in 100,000s. Without an additional performance concern, it seems like a good idea to go forward.
Comment #27
nicxvan commentedJust to add to it, here is the code we used for benchmarking:
We ran it with different classes with different numbers of methods.
The numbers returned are the time to check the class, the time to create the new stdClass and the number of methods:
Comment #28
godotislateNote that this is probably soft-blocked by #3485896: Hook ordering across OOP, procedural and with extra types i.e replace hook_module_implements_alter, or at least there will likely be a giant merge conflict resolution needed between the two.
Comment #29
nicxvan commentedYes let's please postpone this
Comment #30
nicxvan commentedComment #31
godotislateA couple thoughts on issues that might need accounting for, without confirming in code:
If there are complications with either scenario that aren't easy to resolve, then maybe perhaps to reduce scope it can be documented that hooks aren't supported for altered services in whatever use cases and punt those to be done later.
Comment #33
godotislateMR 12222 is up.
Notes:
Drupal\CoreandDrupal\Componentnamespaces and non-Drupal classesregister()to register the kernel test class itself as service and any Hook attributes in the class will be picked upHook\class services that are not registered services. This is because, in order to support altered services, HookCollectorPass has been moved to run after the ModifyServiceDefinitionsPass, so the the Hook class definitions do not exist whenalter()in a service modifier runs (see more below*). IfHook\class behavior needs to be changed, using a service decorator is recommended* For services definitions provided by or modified by service providers to be picked correctly by HookCollectorPass, the defintion additions and alterations need to be registered before HookCollectorPass runs. The only way to get around this otherwise would be to make the HookCollectorPass essentially run twice, once before and once after the ModifyServiceDefinitionsPass. Before moving HookCollectorPass to run after ModifyServiceDefinitionsPass, hook implementations in services registered or modified in ModifyServiceDefinitionsPass would not run anyway. One issue that came up is that if any service provider instantiates the module handler, the hook_implementation_map container parameter needs to exist before that, so that parameter is initialized to an empty array first.
For reference, here's output of a representative local run of
drush si standard -y-vvvv onHEAD:And here's the same output run against the MR branch:
Anecdotally, run time and max memory usage do not seem to be affected too much, even with all module service classes being reflected.
Comment #34
godotislateAdded the CR https://www.drupal.org/node/3526437.
The long, long bit about altered and decorated services in #33 should probably be in the CR as well, but I'm a little tired of typing for now. I can update the CR after there's agreement on that behavior makes sense.
Comment #35
godotislateOK, refactored to split the changes in
HookCollectorPassto a separate pass for hook discovery registered services that runs afterModifyServiceDefinitionsPass. The change now allowsHook\class services that are not registered services to be altered by a service modifier in another module. The code changes are not the prettiest, but I think they are OK.That all being said, changes here are crashing into other in-progress work on OOP hooks in #3506930: Separate hooks from events, #3519561: Introduce ImplementationList objects per hook, to simplify ModuleHandler, and #3526411: [pp-2] Move hook_implementations_map generation to late in service container compilation to make altering hooks classes more DX friendly (among others I'm not aware of?), so I think some sort of priority of what goes in first probably would make things clearer.
It was good to see this working, though, especially the part of making it possible for kernel tests to subscribe to hooks. I think that will be a big DX win once it's in.
Comment #36
nicxvan commentedThank you!
I may have to create a meta, but in my mind for now this is the order I think we should work on these:
#3506930: Separate hooks from events which includes #3519561: Introduce ImplementationList objects per hook, to simplify ModuleHandler
#3526411: [pp-2] Move hook_implementations_map generation to late in service container compilation to make altering hooks classes more DX friendly may not be needed after that change and we may not want to do that at all we need to explore it a bit more.
This issue can likely go after the decoupling from events I would think.
Comment #37
godotislateComment #38
godotislateComment #39
godotislateI think this plan is fine. One thing to note is that this issue, or at least this MR, also fixes a bug (or addresses a feature gap) where currently altering or decorating the autodiscovered
Hook\classes doesn't work quite right. This is because the hook implementation map has the hook class name derived from the PHP file on disk as one of its keys ($this->hookImplementationsMap[$hook][{CLASS NAME}]). The event dispatcher resolves the callable correctly to the altered/decorator class, so callingget_class()on that will make the look up in the map fail (and also cause a PHP warning).On a cursory glance, I think #3526411: [pp-2] Move hook_implementations_map generation to late in service container compilation to make altering hooks classes more DX friendly also tries to address this same bug, but I haven't looked at #3506930: Separate hooks from events enough to see if it's addressed there separately.
In any case, I think there is some urgency to get this bug addressed, regardless of which issue is done in.
Comment #40
nicxvan commentedYes, that bug is concerning, the thing that has me hesitating on both is we're adding an extra compiler pass. Then for this one I'm concerned about performance for two reasons.
1. We need to reflect far more, we had thought that symfony was already reflecting and caching it so we dropped that concern, but we don't have the symfony flag set.
2. We are now rechecking on each hook if it's been changed.
I haven't looked at the event dispatcher issue with an eye to this gap, but I don't think it addresses it.
I need to get a better idea on timing, if this can go into 11.x now that would be good, but I think with 11.2 coming soon we may have to wait a bit, I'm unclear on timing.
Comment #41
godotislate@berdir raised a question about performance concerns iterating through all service definitions. I did a quick test and thought it was worth bringing back to conversation here.
So re-visiting my comments #22 and #26:
autoconfigure: trueas defaults (datetime being at least one exception), so basically all these services are defined as autoconfiguredContainerBuilder::getReflectionClass()does not get called on any of the ctools services when the container is compiled ctools installIf a large majority of the services are already being reflected a compile time, then all those classes are already loaded into memory and my guess is that iterating through another time and reflecting will not have a large performance impact, and #27 seems to back this up.
There could be a noticeable performance impact on a (probably typical) project with dozens of custom and contrib modules with a large number of service definitions that are not autoconfigured or autowired. All those services classes would be loaded into memory and reflected when they otherwise wouldn't.
Comment #42
berdirThanks for the update, sorry if I jumped in without properly reading the existing comments.
Lets revisit this when the separate issue landed (and maybe after the theme issue as that also makes major refactorings to HookCollectorPass and is probably of higher prio). I believe it will be simpler, also thanks to your suggestion on persisting late during compile, so we should able to update the parameters.
on the get_class(), the call you have to change here no longer exists, it's completely gone because we no longer have to reverse-map the module from the listener class. It's part of the hook list structure and readily available. My comment was about the fact that there are two additional get_class() calls in ModuleHandler that might have similar issues but they do not, because they are not expected to map to any existing array keys.
Comment #43
nicxvan commentedUpdating postponement and adding three actual issue postponing this.
Comment #44
godotislateI think that since #3544715: Add oop support to hooks currently supported by themes is in, this is unblocked now. The MR needs refactoring since it was done on the event-based hook collector.
Comment #45
nicxvan commentedOne thing to confirm is if we need to restrict the attribute to classes outside of the hook namespace.
If not then I think we want to go the opposite way and require it to exist on methods only and do this: #3523124: [pp-1] Drop $method parameter from #[Hook] attributes, allow only on methods
Comment #46
godotislateI've started looking at this again and trying to refactor the MR diff into latest 11.x after all the hook collector changes, which are significant.
One thing I noticed is this comment in
HookCollectorPass::collectAllHookImplementations()Since the call to
collectAllHookImplementations()fromModuleHandler::add()was removed in #3528899: ModuleHandler::add() removes implementations from other modules, I think it will help here a lot to changecollectAllHookImplementations()to protected, static, with only the$containerargument in this issue per that @todo, so I'll likely proceed that way.Comment #47
nicxvan commentedI think that's reasonable
Comment #48
godotislateSo there are complexities between altering services with decorators or module service providers, and the Order* and Remove attribute functionality. These were kinda obscured when the hook collector leveraged the event system, and some things magically worked because the event system resolves callables at run time with the use of service closures.
To simplify things a bit, let's stipulate that all the
Hook\namespace classes are not meant to be altered or decorated in any way, and that Order/Remove hooks are the only to affect the behavior of existing hooks. We'd just document that trying to alter or decorate a Hook class is not supported and may result in unexpected or unpredictable behavior.This leaves us with hook-implementing services that we're looking to do here. Conceivably people will declare their services that have both Hook and non-Hook methods, and likely there will be people who will want to alter or decorate those services. In which case, what is the expected behavior? As mentioned, with the event system, hook functions would only be invoked on the class that actually resolved from the service ID at runtime. With the new implementation of how hook classes are registered, this won't happen (for decorated services at least) without some significant refactoring.
Anyway, the outstanding questions are:
Comment #49
geek-merlin@godotislate #48: [Proposal to not support service-with-hook decoration.]
The idea to limit scope sounds reasonable. TBH i do not understand the ramifications or alternatives of this (maybe i missed a relevant comment when vgrepping.)
I see two different cases:
a) One foo.service both implentis an interface AND implents a hook (not being part of that interface). While i would NOT recommend this for "clean-ness", it totally can be done. Another bar.service decorates foo.service interface methods, not caring for the hook.
=> My expectation is that the hook still runs in the (now renamed) bar.service.inner (ex foo.service).
b) One foo.service implements (say) hookEntityPreSave, and another component wants to wrap that hook.
=> This has relevant complexities, and it has my +1 to say it's unsupported and defer it to a separate issue "Allow hook implementations to be wrapped".
Some thoughts on b)
- Hux has a dedicated attribute for it.
- My gut feeling is not NOT support decorating the hook-implementing service, as it may contain multiple hook implementations. And it's not a well-defined interface that we're decorating, but the "interface" is a single hook implementation and its signature, NOT all public methods, because Hook service classes tend to have hook implementations added over time, For the same reason, let's stick with the term "wrap a hook implementation", because wrapping a hook implementationis technically not decorating.
@godotislate Is this along your lines of thought?
Comment #50
godotislateRe #49, I think we are basically in agreement. Though I would add that module service provider altering service definitions are also an issue here, and after trying some experimentation and consideration, I think
Comment #51
godotislateGiven this some more thought, and this is a plan I think is implementable:
Drupal\Corenamespace can have Hook implementationsHook/RemoveHook/ReorderHookattributes in the new class will be ignored completely. The methods in the original class that are Hook implementations will still be invoked with the hookclassproperty set will not be part of Hook discovery. This includes services that are created from afactoryor aparentwithout aclass. In addition,abstractandsyntheticservices are excluded from Hook discovery. Maybe an exception is possible for service definitions that are NULL, such as
Drupal\example\Service: ~, but that will need some investigationGeneral implementation plan:
class. Exclude discovery on definitions that areabstract,synthetic, or have adecoratespropertyModifyServiceDefinitionsPassComment #52
godotislateProviding an example of the issue with altered services for clarity.
We have a service that has two hook methods:
We have another service that removes the
OriginalService::testAhook:And another service that reorders
OriginalService::testB:Now let's say we have a new class
AlteredServicethat a module service modifier changes the definition of theOriginalServiceservice:And
AlteredServicelooks like this:Or similarly a new class
DecoratedServicethat a service decorator uses to replaceOriginalService:The complexity is this:
The
RemoveHookandReorderHookinReorderHookServiceandReorderHookServicetarget methods inOriginalService. But if the modules that provideAlteredServiceorDecoratedServiceare installed, thenOriginalServicehas been replaced, so what behavior should theRemoveHookandReorderHookhave?So in order to not have to deal with that complexity, I think the simplest way would be for
testAandtestBinOriginalServicenot to be affected by theAlteredServiceorDecoratedServicemethods at all. Meaning that even if the service definition has been changed, the hook methods in OriginalService are still invoked, unless aRemoveHooksomewhere targets them.The idea in #51 is that the hook methods in
AlteredServiceandDecoratedServicewould not be registered as hook implementations at all.An alternative idea would be that the hooks in OriginalService, and AlteredService or DecoratedService, are all registered. For decorated services, this would actually mean that every hook method in every class in the decorator chain would be registered. I think to implement this, we'd have to do two collector passes, before and after
ModifyServiceDefinitionsPass, and loop through all the service definitions both times. (The Hook namespace discovery would still only happen the first time). This way the classes for the service definitions before being modified would be registered, as well as the classes after.Comment #53
godotislateHad a quick convo with @nicxvan about this on Slack, and a couple more notes:
OriginalServicehooks still work might be a problem, because thecallableResolvermight not be able to instantiate theOriginalServiceclass correctly at run time. (I was observing something different in testing, but what I was seeing could have a different explanation)Remove/Reorderwould likely be ignored if there's no match, but there might need to be refactoring in thatRemove/Reordershould targetservice_id:methodinstead ofclass_name:method(except when the class name is the service ID)Remove/Reordertarget service IDs, that means that they would work on the class the service ID resolves to. So in the example in #52, they would work against AlteredService or DecoratedService hooksComment #55
godotislateComment #56
godotislateComment #57
godotislateComment #59
nicxvan commentedThis is very tricky and I think will need wider consensus.
Honestly we needed to think about what is most expected and least likely to break things.
I would think we'd try to pattern it around how we handle RemoveHook and ordering which is if anything doesn't align we discard the directive.
Honestly I think the outermost level is responsible for calling inner and maintaining parity.
I think the trickier situation is when only one layer has the attribute or a layer is skipped.
I lean towards last being canonical.
If you're decorating or altering is up to you to keep up to date. I think the most predictable would be we should discard inner directives.
I'm 100% open to other thoughts and opinions though.
Comment #60
donquixote commentedI see that #3523124: [pp-1] Drop $method parameter from #[Hook] attributes, allow only on methods was postponed for this issue, because we were considering to put attributes on class level for performance.
I think this is no longer relevant, is it?
I think it would feel odd to have different attribute placement rules for classes in \Hook\ and elsewhere.
If performance is a concern, we should somehow tag services that have hooks.
A module could even tag all their services using defaults.
But I think we are already over that, based on the comments I saw.
I think we can resume the discussion in the other issue.
Comment #61
godotislateI think looping through all the methods in a class and all the registered services (or all classes in a directory) are separate performance issues.
If/when we resolve outstanding architecture questions in the IS, it would make sense to do a performance test on container building with a site that contains a lot of contrib and custom modules whose services are largely not autoconfigured or autowired.
Since
autoconfigureis in effect for almost all core services, those classes are already being reflected, so reflecting them again for Hook discovery does not increase memory use and is likely not a significant CPU issue. On a site where a lot of contrib/custom services are not already being reflected for autoconfigure or autowire, then the amount of memory discovery uses loading the classes for reflection comes into play more. And yes, this could be addressed per @berdir's suggestion earlier that registered services with Hooks would need both a service tag and the Hook attributes.Comment #62
donquixote commentedWhat would be the value of $module when these implementations are invoked?
Also in other cases where services have hooks, can we always reliably determine a module name?
E.g. if a module registers a service using a class from a non-Drupal package in /vendor/, could that have hooks? And what would be $module?
(Seems unfair if we don't allow that, but core is allowed to do it :) )
The case of module invokers that use the $module for anything is quite rare, but for now it is still part of the contract, and it can be expected to be a valid module name (e.g. "core" is not).
Comment #63
godotislatecore. We already did this in #3502432: Make hook testing with kernel tests very simple.Comment #64
donquixote commentedI would expect that scanning the methods on an already reflected class will have a very small impact compared to loading the class file, unless we do something expensive like parsing the doc comment of each method - which we don't. Or if we would rely on something like static reflection parser, which does not load the full file and can be faster if we only parse the top.
Comment #69
godotislateOK, I think I figured out a way forward that avoids some complexity. It's up for review: MR 15722.
It's getting late, so will summarize briefly here and then update IS/CR later.
The main idea is to make the hook attribute Order API the only way to alter and reorder hooks, and to prevent interaction with altering container services by decorators or module service modifiers/providers.
How this is done:
hooktag is added to them"hook.{class name}". This is done to allow decorators and service providers to alter a registered service without changing the actual hook implementationshookare looped through to make sure that the class associated with the service has not changed. This prevents service modifiers or decoration from changing the actual hook servicesComment #70
godotislateComment #71
godotislateUpdated the IS and CR.
Comment #72
godotislateHad a thought that maybe it'd be fine to allow service decorators to be included in hook discovery. My thought about excluding them was to make service modifiers and service decorators have parallel functionality. But since decorators and modifiers don't work identically anyway, it could make sense to include decorators, if for no other reason than for somehow to define a service decorator that has a RemoveHook method that targets the hook implementation in the original service class.
The idea would be that hook implementations in every decorating class and the original service would all have their hooks run, and that Order/Remove/etc would still target the actual class they are in.
The protection that validates that "hook"-tagged services are not altered or decorated would remain in place.
Comment #73
godotislateBumped the CR version to 11.5, since this seems unlikely to get in for 11.4. I don't see any deprecations in the MR, so we should be good there.
Comment #74
macsim commented@rodrigoaguilera said in #3
I opened an issue a few months ago for a similar need with hook_theme #3558998: Allow multiple hook_theme implementations per module
Comment #75
nicxvan commentedOk I took a first pass review, I'm glad I'm seeing the less complex version :D.
I have some questions, I am concerned about the complexity, I don't fully get the bit in the later compiler pass.
I have not reviewed the tests fully, but I will need to.
Comment #77
godotislateOK, I opened draft MR 15981 to demonstrate what the current state of replacing a Hook class via a service modifier
alter()method or decoration is. For the following examples, replacing the class via altering or decorating ends up being functionally the same.module_ahas classDrupal\module_a\Hook\ATestHookswith methodtestHookthat implements hooktest_hook, then ifmodule_breplaces that class withDrupal\module_b\BTestHooksin the hook service definition, andBTestHookshas or inheritstestHook, thenBTestHooks::testHookwill run whentest_hookis invoked, andATestHooks::testHookdoes not runBTestHooks::testHookdoes not exist, there will be an invalid argument exception whentest_hookis invokedmodule_chas classDrupal\module_c\Hook\CTestHookswith a method testCHooks that implementstest_hookthat looks like:Then
testCHookswill run beforeBTestHooks::testHook.ATestHooks::testHookstill does not run. TheclassesAndMethodsparameter is slightly misleading; it actually targets service IDs because of how the callable resolver works. It's just that in the class of Hook\ classes, the service ID is the FQCN.module_chas Hook class methods that targetATestHooks::testHook, thenBTestHooks::testHookis actually the method is that ordered against or removed.(Note that for decorating, the above applies only to the outermost decorator. Inner decorators are ignored.)
I think this is confusing and can lead to errors. What is proposed in MR 15722 is that decorating or altering Hook\ class service definitions is prohibited. This means that hook will always run in the original Hook class. While this is a breaking change for any projects that were replacing Hook services, I'm not sure what BC we're obligated here to, because this pattern was not established as part of API. Perhaps we could do some kind of deprecation here, in which case we should define what that deprecation behavior looks like.
In addition, as the MR expands hook discovery to any registered service, this means that "classes" still can be targeted, without needing to change the "classesAndMethods" or "class" parameter names, because the collector will register a second ID (of the form "hook.{FQCN}" for the service. It's also prohibited to decorate or alter the
hook.classes, which is not a break, since these are new.Comment #78
godotislateI made changes to the MR and CR so that decorating or altering Hook\ services is deprecated.
Comment #79
needs-review-queue-bot commentedThe Needs Review Queue Bot tested this issue. It no longer applies to Drupal core. Therefore, this issue status is now "Needs work".
This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.
Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.
Comment #80
godotislateRebased after merge conflict in HookCollectorPass from #3592577: Ensure that hook attributes are never parsed from a stale opcache.