Jump to content

Create a hook in ready.php that can also be used in a template file


a-ok
 Share

Recommended Posts

Is it possible to create a hook in ready.php that can also be used in a template?

I’m using a REST API for Shopify to create pages in the backend (a list of products) but I also want to loop this list of products in a template file. I don’t want to have to write two hook functions that is essentially the same code.

My hook is set to fire via lazyCron every 30 mins (LazyCron::every30Minutes)

Link to comment
Share on other sites

Hi, I think we could say that ready.php is one of the file where we can define hooks to alter templates. It could also be a module.

So yes, it's possible and it's the way to go and it depend only on the context you put your hook on.

Link to comment
Share on other sites

1 minute ago, flydev said:

Hi, I think we could say that ready.php is one of the file where we can define hooks to alter templates. It could also be a module.

So yes, it's possible and it's the way to go and it depend only on the context you put your hook on.

Thanks.

So if I set an array in ready.php I could essentially access it in a template if the hook context is correct?

Link to comment
Share on other sites

1 hour ago, flydev said:

Yes, to be more precise, as it look like you want to access this array from a template, you will want to set this array as a property to the right page id or template context.

Check :


wire()->addHookProperty(...);

https://processwire.com/api/ref/wire/add-hook-property/

Amazing.

And do you know if it’s possible to pass patamters into addHookProperty to pass an ID, for example, from when it’s used at the template end? So I can use the property but set different parameters.

Link to comment
Share on other sites

44 minutes ago, a-ok said:

And do you know if it’s possible to pass patamters into addHookProperty to pass an ID, for example, from when it’s used at the template end? So I can use the property but set different parameters.

// in ready.php

$someID = 1000;
// Adding a hook property
$wire->addHookProperty('Page::customProperty', function($event) use($someID) {
    $page = $event->object;
    $event->return = $someID;
});

// in home.php template file, for example
echo $page->customProperty;// 1000

notice the use()...It's a PHP thing. I can't find a reference to it ATM.

Edited by kongondo
  • Like 1
Link to comment
Share on other sites

Two examples I've used.

//Page "intro" property that can be accessed via $page->intro:
wire()->addHookProperty('Page::intro', function($event) {
    $page = $event->object;
    if ($page->summary) { //some pages on the admin do not have a summary field, only body
        $intro = strip_tags($page->summary);
    } else {
        $body = strip_tags($page->body);
        $intro = $body;        
        $length = 450;
        if (strlen($body) > $length) {
            $intro = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $intro);
        }
    }
    $event->return = $intro;
});

// I have a computed page_views field. If the page is a podcast, I added the views from Soundcloud to the page_total_views hook.
wire()->addHookProperty('Page::page_total_views', function($event) {
    $page = $event->object;
    $views = 0;
    if ($page->soundcloud_playback !== "") { //if page has a soundcloud field, it's a podcast page
        
        $page->of(false);
        
        $en = wire('languages')->get("default");
        $soundcloud_playback_en = intval($page->getLanguageValue($en, 'soundcloud_playback')); // get the unformatted value in English

        $pt = wire('languages')->get("pt");
        $soundcloud_playback_pt = intval($page->getLanguageValue($pt, 'soundcloud_playback')); // get the unformatted value in Portuguese
            
        $views = intval($page->page_views) + $soundcloud_playback_en + $soundcloud_playback_pt;
        
    } else {
        $views = $page->page_views;
    }
    $event->return = $views;
});

 

Link to comment
Share on other sites

11 hours ago, kongondo said:

// in ready.php

$someID = 1000;
// Adding a hook property
$wire->addHookProperty('Page::customProperty', function($event) use($someID) {
    $page = $event->object;
    $event->return = $someID;
});

// in home.php template file, for example
echo $page->customProperty;// 1000

notice the use()...It's a PHP thing. I can't find a reference to it ATM.

Thanks again!

Apologies for not explaining but I meant using different parameters in the template like a standard PHP function:

$page->customProperty(2) or $page->customProperty(1373, 1786) with the arguments being different each time.

For example say I created this hook in ready.php

$this->http = new WireHttp();
$this->host = 'xxx.myshopify.com';
$this->shopifyAPIKey = 'xxx';
$this->shopifyPassword = 'xxx';
$this->shopifyBase = 'https://' . $this->shopifyAPIKey . ':' . $this->shopifyPassword . '@' . $this->host . '/admin/';

$wire->addHookProperty('Page::shopifyRelatedProducts', function($event) {
	$page = $event->object;
	//$event->return = $this->http->getJSON($this->shopifyBase . 'products.json?ids=632910392,921728736');
	$event->return = $this->http->getJSON($this->shopifyBase . "products.json?ids=$shopifyProductIds");
});

On a template (say home.php) when I call the new hook property how would I pass in the arguments for the parameter $shopifyProductIds?

$ids = "123456,789101"
$page->shopifyRelatedProducts($ids);

 

Link to comment
Share on other sites

2 hours ago, a-ok said:

I meant using different parameters in the template like a standard PHP function:

You want to add a method then; not a property :-).

Wire::addHookMethod() 

https://processwire.com/api/ref/wire/add-hook-method/

http://processwire.com/api/hooks/#add_new_method

Inside the hook, you can get your parameters using event->arguments. E.g. event->arguments(0) is the first parameter, event->arguments(1), the second one, etc.

Edited by kongondo
  • Like 2
Link to comment
Share on other sites

12 minutes ago, kongondo said:

You want to add a method then; not a property :-).

Wire::addHookMethod() 

https://processwire.com/api/ref/wire/add-hook-method/

http://processwire.com/api/hooks/#add_new_method

Inside the hook, you can get your parameters using event->arguments. E.g. event->arguments(0) is the first parameter, event->arguments(1), the second one, etc.

Yes! This is great! ?

Thanks everyone.

A final thing. I was using phpFastCache before but I'd like to use the in-built $cache. I'm guessing this is possible within a hook? Just so I can cache the API JSON every 30 minutes or so.

Link to comment
Share on other sites

1 minute ago, a-ok said:

but I'd like to use the in-built $cache. I'm guessing this is possible within a hook? Just so I can cache the API JSON every 30 minutes or so.

Of course. All ProcessWire API is available everywhere :-). In a function wire('cache') should do the trick. I think there are other variants of that but I never use them myself.

  • Like 1
Link to comment
Share on other sites

Amazing.

I did the following:

$wire->addHookMethod('Page::shopifyRelatedProducts', function($event) {
	$page = $event->object;
	$shopifyProductIds = $event->arguments(0);
	$result = wire('cache')->get('shopifyRelatedProductsForPage' . $page->id, WireCache::expireHourly);
	if (!$result) {
		$result = $this->http->getJSON($this->shopifyBase . "products.json?ids=$shopifyProductIds");
		wire('cache')->save('shopifyRelatedProductsForPage' . $page->id, $result, WireCache::expireHourly);
	}
	$event->return = $result;
});

Which seems to work but how can I check it's loading the cached version? Do you know where the WireCache files are saved?

EDIT

I guess it has worked!

100275146_ScreenShot2018-11-20at11_07_41.thumb.png.968501730f514673423d3dc058ffe4c8.png

Edited by a-ok
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.
×
×
  • Create New...