Jump to content

Hooks inside hooks possible?


Gadgetto
 Share

Recommended Posts

Hi guys (didn't see any gals here),

I have a module which has some custom helper classes. One of these classes has methods which are hookable. The class is derived from WireData. An additional complication is that this class has its own namespace. What would be the correct way to provide the hookable methods via API?

Here is a very simplified code sample of the class:

<?php
namespace SnipWire\Services;

use ProcessWire\WireData;
use ProcessWire\WireException;

class Webhooks extends WireData {

    ...

    public function ___handleOrderCompleted() {
        if ($this->debug) $this->wire('log')->save(
            self::snipWireWebhooksLogName,
            '[DEBUG] Webhooks request: handleOrderCompleted'
        );
        $this->responseStatus = 202; // Accepted
    }

    public function ___handleOrderStatusChanged() {
        if ($this->debug) $this->wire('log')->save(
            self::snipWireWebhooksLogName,
            '[DEBUG] Webhooks request: handleOrderStatusChanged'
        );
        $this->responseStatus = 202; // Accepted
    }

    ...
}

The class itself is invoked/used by a hook from within the main module:

Depending of the event, one of the methods of the Webhooks class above is triggered. A developer should now be able to use one of the ___handle* methods to do further things.

    /**
     * Check for webohook request and process them.
     * (Method triggered before ProcessPageView::execute)
     *
     */
    public function checkWebhookRequest(HookEvent $event) {
        if ($webhooksEndpoint = $this->get('webhooks_endpoint')) {
            if ($this->sanitizer->url($this->input->url) == $webhooksEndpoint) {
                /** @var Webhooks $webhooks Custom ProcessWire API variable */
                $this->wire('webhooks', new Webhooks());
                $this->wire('webhooks')->process();
                $event->replace = true;
                // @note: Tracy Debug won't work from here on as normal page rendering is omitted!
            }
        }
    }

Should I provide a custom API variable e.g. $webhooks? Or how is the best way to do this?

Edited by Gadgetto
Changed post title
Link to comment
Share on other sites

Hey @Gadgetto did you find a solution for your problem?

On 3/10/2020 at 6:21 PM, Gadgetto said:

$this->wire('webhooks')->process();

What does that do?

I'm still not sure I understand the problem completely and the best solution in more complex setup always depends on the situation, but maybe you could make a proxy method in your main module that is hookable instead of making all methods in the helper module hookable? Some untested pseudo-code:

// main module SnipWire
public function webhooks(...$args) {
	$helper = $this->get('webhooks_endpoint')
	if($args['foo']) return $helper->foo(...$args); // returns "foo"
	if($args['bar']) return $helper->bar(...$args); // returns "bar"
	...
}


// site/ready.php
$wire->addHookAfter("SnipWire::webhooks", function($event) {
	$name = $event->arguments('name');
	if($name != "foo") return;
	$event->return .= " hooked";
}

// then the foo webhook should return "foo hooked" instead of "foo"

 

Link to comment
Share on other sites

Hi @bernhard, thanks for jumping in!

14 hours ago, bernhard said:
On 3/10/2020 at 6:21 PM, Gadgetto said:

$this->wire('webhooks')->process();

What does that do?

The Webhooks class handles Snipcart's web hook events and provides hookable methods to attach custom code to those events. eg. orderCompleted, customerUpdated, ad so on ... A Snipcart webhook event is a POST request which is sent to your site by Snipcart. Each POST request holds json encoded data corresponding to the specific situation. e.g. A orderCompleted event POSTs the full order array to your site.

The Webhooks class is available as custom API variable $webhooks.

This code in SnipWire main module takes over POST request from Snipcart:

    /**
     * Check for webohook request and process them.
     * (Method triggered before ProcessPageView execute)
     *
     */
    public function checkWebhookRequest(HookEvent $event) {
        if ($webhooksEndpoint = $this->get('webhooks_endpoint')) {
            if ($this->sanitizer->url($this->input->url) == $webhooksEndpoint) {
                $this->wire('webhooks')->process();
                $event->replace = true;
                // @note: Tracy Debug won't work from here on as normal page rendering is omitted!
            }
        }
    }

This line...

$this->wire('webhooks')->process();

... starts the process which handles a Snipcart POST request:

https://github.com/gadgetto/SnipWire/blob/cc9922fbe059b3961d3ee63be253e34d4cf96bc1/services/Webhooks.php#L108

Within this processing the specific hookable method within the Webhooks class is called. I thought it should be easy to provide those methods a hookable. But it seems this isn't so easy with custom classes.

For example - this doesn't work:

$webhooks->addHook('handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 

and also not this:

$webhooks->addHook('Webhooks::handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 

or this:

$wire->addHook('Webhooks::handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 

 

Link to comment
Share on other sites

Just tried and it works just as you expected it to work:

4DH1qQh.png

That's why I was asking what the process() does exactly (code!).

<?php namespace RockSearch;
use ProcessWire\Wire;
class Matcher extends Wire {
  public function ___foo() {
    return 'foo';
  }

 

Link to comment
Share on other sites

1 hour ago, bernhard said:

class Webhooks extends WireData {

I guess WireData does not support hooks whereas Wire does.

From PW docs:

Quote

To make a class capable of having hookable methods, simply extend one of ProcessWire's classes such as Wire or WireData as your base

So it should work. 😕

Link to comment
Share on other sites

Of course it does, as WireData extends Wire, sorry for that 🤦‍♂️

Does it work if you call $this->handleOrderCompleted() directly? Maybe the dynamic method call is the problem (wouldn't know why, though). Maybe it is working, but you just think it is not. How do you check if it is working? 😉 

Link to comment
Share on other sites

1 hour ago, bernhard said:

Of course it does, as WireData extends Wire, sorry for that 🤦‍♂️

Does it work if you call $this->handleOrderCompleted() directly? Maybe the dynamic method call is the problem (wouldn't know why, though). Maybe it is working, but you just think it is not. How do you check if it is working? 😉 

I have this part in my ready.php

$webhooks->addHook('handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 

But the log entry isn't written.

Link to comment
Share on other sites

34 minutes ago, Gadgetto said:

I have this part in my ready.php


$webhooks->addHook('handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 
13 minutes ago, Gadgetto said:

Could be a bug in PW...

No, it is a bug in your hook 😉  You are adding a new method with your hook, not hooking into that method! You are simply missing the addHookAFTER

$webhooks->addHookAfter('handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 

 

Link to comment
Share on other sites

44 minutes ago, bernhard said:

No, it is a bug in your hook 😉  You are adding a new method with your hook, not hooking into that method! You are simply missing the addHookAFTER


$webhooks->addHookAfter('handleOrderCompleted', function($event) {
	wire('log')->save('webhookstest', 'hook works');
}); 

 

I changed to addHookAfter but still doesn't work. (had this tried before without success) 🤔

Link to comment
Share on other sites

Are you sure? Maybe I don't understand this correctly... It seems a new method is only added if the specified method name doesn't exist.

From the docs:

---

You can add new methods to any ProcessWire class in the same way that you would hook an existing method. The only difference is that the method doesn't already exist, so you are adding it. Also, because there is no distinction of "before" or "after" for something that doesn't already exist, you can attach the method using addHook(); rather than addHookBefore(); or addHookAfter() … though technically it doesn't really matter what you use here. Lets say that you wanted to add a new method to all Page instances that outputs a relative time string of when the page was last modified (for example, "45 minutes ago" or "3 days ago", etc.):

public function init() {
  $this->addHook('Page::lastModified', $this, 'lastModified');
}

public function lastModified($event) {
  $page = $event->object;
  $event->return = wireRelativeTimeStr($page->modified);
}

Hooking both before and after
If you want your hook method to run both before and after a particular event occurs, you can specify that in an $options array to the addHook() call, like this:

$wire->addHook('Class::method', function(HookEvent $e) {
  // ...
}, [ 'before' => true, 'after' => true ]); 
Link to comment
Share on other sites

Changed to a static method call - still not working... 🤯

I'm just thinking it could be a problem that the process() method (which calls the hook method dynamically) itself is also triggered by a hook?

public function init() {
    ...
    $this->addHookBefore('ProcessPageView::execute', $this, 'checkWebhookRequest');
    ...
}

/**
 * Check for webohook request and process them.
 * (Method triggered before ProcessPageView execute)
 *
 */
public function checkWebhookRequest(HookEvent $event) {
    if ($webhooksEndpoint = $this->get('webhooks_endpoint')) {
        if ($this->sanitizer->url($this->input->url) == $webhooksEndpoint) {
            $this->wire('webhooks')->process();
            $event->replace = true;
            // @note: Tracy Debug won't work from here on as normal page rendering is omitted!
        }
    }
}

 

Link to comment
Share on other sites

Quote

it could be a problem that the process() method (which calls the hook method dynamically) itself is also triggered by a hook

Could this be a bug in PW or is it intentional? Should I file an issue?

Any ideas from the other pros here? I'm really stuck with this. 😞 

Link to comment
Share on other sites

Just now, Gadgetto said:

Could this be a bug in PW or is it intentional? Should I file an issue?

I'd first confirm that this is really the problem by putting together a test-setup that makes the issue reproducable. It is definitely possible to add hooks inside hooks, but timing is very important! https://processwire.com/blog/posts/new-ajax-driven-inputs-conditional-hooks-template-family-settings-and-more/#new-conditional-hooks

So I think it's more likely a problem in your code than a bug in PW... 

Link to comment
Share on other sites

59 minutes ago, bernhard said:

I'd first confirm that this is really the problem by putting together a test-setup that makes the issue reproducable. It is definitely possible to add hooks inside hooks, but timing is very important! https://processwire.com/blog/posts/new-ajax-driven-inputs-conditional-hooks-template-family-settings-and-more/#new-conditional-hooks

So I think it's more likely a problem in your code than a bug in PW... 

I'll try to write a small test case. Thanks again @bernhard!

Link to comment
Share on other sites

That's strange. I've just realized that I did exactly the same in one of my modules and prepared methods to be hookable (just in case I'd need it one day) and those hooks do also not get triggered. The strange thing is that this little module works just as expected:

<?php namespace ProcessWire;
class RockHook extends WireData implements Module {

  public static function getModuleInfo() {
    return [
      'title' => 'RockHook',
      'version' => '0.0.1',
      'summary' => 'RockHook',
      'autoload' => true,
      'icon' => 'bolt',
      'requires' => [],
      'installs' => [],
    ];
  }

  public function init() {
    $this->addHookAfter("ProcessPageView::execute", function(HookEvent $event) {
      $this->hello("trigger hello() in execute() hook");
    });
    $this->addHookAfter('hello', function(HookEvent $event) {
      bd('hello hooked in RockHook::init()');
    });
  }

  public function ___hello($where) {
    bd('hello!', $where);
  }
}
// in site/ready.php
$this->addHookAfter('RockHook::hello', function(HookEvent $event) {
  bd('hello hooked in /site/ready.php');
});

7ZOmZDg.png

Edit: Attaching the hook like this does also work:

<?php namespace ProcessWire;
class RockHook extends WireData implements Module {

  public static function getModuleInfo() {
    return [
      'title' => 'RockHook',
      'version' => '0.0.1',
      'summary' => 'RockHook',
      'autoload' => true,
      'singular' => false,
      'icon' => 'bolt',
      'requires' => [],
      'installs' => [],
    ];
  }

  public function init() {
    $this->addHookAfter("ProcessPageView::execute", $this, "handleWebhook");
    $this->addHookAfter('hello', function(HookEvent $event) {
      bd('hello hooked in RockHook::init()');
    });
  }

  public function handleWebhook($event) {
    $this->hello("trigger hello() in execute() hook");
  }

  public function ___hello($where) {
    bd('hello!', $where);
  }
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By nuel
      Hi
      I'm working with PW for some time now, but – please don't laugh – never used hooks.
      I have 200 – 300 subpages with the template 'artist', the title of each page represents the full name, sometimes John Doe, sometimes John Emmet Brown Doe. I want to auto-populate the field 'artist_last_name' with the word that is most likely the last name, the last word of the page title. If there are more names, it can be changed manually. I need this for easier and quicker alphabetical sorting.
      What I put together is this, in ready.php. Doesn't work. Again, I'm new to hooks..
      <?php     $wire->addHookBefore('Pages::saved', function(HookEvent $event) {     $p = $event->arguments('page');     if($p->template != 'artist') return;     if($p->artist_last_name) return;     $ln = end(explode(' ', $p->title));     $p->set('artist_last_name',$ln);     }); ?> In the best case this would be done once globally without having to open and save every page. But new pages should populate the field on page save.
      Thanks for your help, I think it's easy, I just need a push..
      Nuél
    • By rjgamer
      Hi,
      is there a hook after the current (active) page got created? Or which method got called in the Page class after the Constructor of the current page got initialized?
      Thanks.
       
    • By Kiwi Chris
      I need to restrict editing access based on both the user role, and the value of a sub-field in a page reference field.
      eg $page->competition->closingDate 
      There's some discussion about restricting editing access based on role, and that works, but when I try to access the page via the method @Robin S suggests, the page returned is an admin page rather than the page being edited, so I don't have access to the edited page's fields.
       
    • By picarica
      so i am trying to put CustomHooksForVariations.module, a custom module, i am placing it into site/modules direcotry yet my modules page in admin panel gives me errors
      so this is the screen show when i refresh modules, i dont know why the shole hook is written on top of the page :||

      and this next image is when i try to install it, i saw that it is not defiuned modules.php but it shouldnt need to be ?, any ways i dont want to edit site's core just to make one moulde work there has to be a way

    • By Andi
      Continuing my journey into PW hooks, I'm trying to find a way to retrieve all images from a page that explicitly *do not* have a certain tag (or tags) attached to them.
      Found this post from 2015
      But I'm wondering if there's a more elegant way to go about this.
      Let's say I have a multi-image field called "images_header" and instead of
      $page->images_header->findTag('mytag'); I would like to do this:
      $page->images_header->excludeTag('mytag'); So I'd be able to do
      // find images that don't have the tag "mytag" $images = $page->images_header->excludeTag('mytag'); // check if there's any images if (count($images)>0) { // do something.. } Would this be possible by hooking into Pagefiles somehow?
      There's this bit in /wire/core/Pagefiles.php Line 626 that I'd basically just need to reverse (or at least in my mind 😄 )
      public function findTag($tag) { $items = $this->makeNew(); foreach($this as $pagefile) { if($pagefile->hasTag($tag)) $items->add($pagefile); } return $items; } Any ideas on how this could be done in a graceful manner?
      Thanks in advance!
×
×
  • Create New...