addListener $functionName parameter type

Welcome to the WonderCMS community. Anything goes, except for support requests.
Post Reply
User avatar
StephanStanisic
Posts: 37
Joined: Fri Jul 05, 2019 8:51 pm

addListener $functionName parameter type

Post by StephanStanisic »

So this is me trying to get a few opinions on this following problem/proposal I have.

Let's say a plugin get's created, but it is in the OOP style.
When I want to add a listener on something, the addListener function expects a string.
The PHP documentation for the variable function shows us that you can call a function part of a class, but you'd have to pass an array.
WonderCMS (3.0.0) defines the type of the $functionName varable as string, so it isn't possible to attach a class.

My proposal:
Change the type hinting to callable instead of string. This way both strings and arrays can be allowed.

Is this something that we should change in the WonderCMS core, or a problem for the plugin to solve?





Example plugin:

File: test/test.php

Code: Select all

<?php

class Test {

	public function __construct() {
		global $Wcms;
	
		// Attach a listener on the menu
		$Wcms->addListener('menu', [$this, "menuListener"]);
	}
	
	public function menuListener(array $args) : array {
		$args[0] .= "Do something else";
	
		return $args;
	}

}

$Test = new Test();
Edited function in WonderCMS core:

Code: Select all

public function addListener(string $hook, string $functionName): void
{
	$this->listeners[$hook][] = $functionName;
}

Code: Select all

public function addListener(string $hook, callable $functionName): void
{
	$this->listeners[$hook][] = $functionName;
}
User avatar
wiz
Posts: 754
Joined: Sat Oct 30, 2010 12:23 am

Re: addListener $functionName parameter type

Post by wiz »

This has been approved and merged to experimental repository.

Thanks Stephan!
Post Reply