PHP Classes

File: ACTIONS.md

Recommend this page to a friend!
  Classes of Johnny Mast   PHP Filters and Actions   ACTIONS.md   Download  
File: ACTIONS.md
Role: Auxiliary data
Content type: text/markdown
Description: Auxiliary data
Class: PHP Filters and Actions
Listen to events and execute registered actions
Author: By
Last change:
Date: 6 years ago
Size: 1,827 bytes
 

Contents

Class file image Download

Excute action with callback

function func_hello_world($text) {
    echo $text."\n";
}
Sandbox\Actions::add_action('hello_world', 'func_hello_world');
Sandbox\Actions::do_action('hello_world', 'Hello World');

*Output*

$ php ./actions.php
Hello World

Actions with closures

Sandbox\Actions::add_action('hello_world', function () {
    echo "The callback is called\n";
});
Sandbox\Actions::do_action('hello_world');

*Output*

$ php ./actions.php
The callback is called

Actions with priority

function func_second($text) {
    echo "Called second\n";
}

function func_first($text) {
    echo "Called first\n";
}

Sandbox\Actions::add_action('say_hello', 'func_second', 1);
Sandbox\Actions::add_action('say_hello', 'func_first', 0);
Sandbox\Actions::do_action('say_hello');

*Output*

$ php ./actions.php
Called first
Called second

Actions within classes

class Action {

    public function func_second($text) {
        echo "Called second\n";
    }

    public function func_first($text) {
        echo "Called first\n";
    }


    public function execute() {

        Sandbox\Actions::add_action('say_hello', [$this, 'func_second'], 1);
        Sandbox\Actions::add_action('say_hello', [$this, 'func_first'], 0);

        return Sandbox\Actions::do_action('say_hello');
    }
}

$instance = new Action;
$out = $instance->execute();
$ php ./actions.php
Called first
Called second

Chaining actions

Sandbox\Actions::add_action('say_hi', function($name='') {
    echo "Hi: ".$name."\n";
});

Sandbox\Actions::add_action('say_bye', function($name='') {
    echo "Bye: ".$name."\n";
});

Sandbox\Actions::do_action(['say_hi', 'say_bye'], 'GitHub');

$ php ./actions.php
Hi: GitHub
Bye: GitHub