hook

Gesponsorde koppelingen

PHP script bestanden

  1. hook

« Lees de omschrijving en reacties

Eerst zie je de twee bij elkaar horende classes, gevolgd door een voorbeeldje die het principe laat zien.


--- class.hook.php ---

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
/**
 * PHP Class - Hook
 *
 * Create hooks in which callbacks can be stored together with their arguments so they can be called later. This can be a serious advantage
 * in extendability and flexibility of an application.
 * For example: Creating hooks enables the possibility of modifying behaviour by loading plugins without the need to rewrite the code where
 * the modification is wanted. It also makes sure modification of behaviour is only possible on places where it is allowed: on places where
 * a hook is executed.
 *
 * @author Emiel Klein Ovink
 * @link http://www.kleinovink.net, http://www.sparkle6.com
 * @copyright 2008
 */


class Hook {


    private $insert_id;     // Integer which will be increased by 1 every time a callback is added.
    private $callbacks;     // Array containing the callbacks.

    
    /**
     * ::__construct( void )
     *
     * Constructs a new instance of the hook and initializes the insert_id and the array
     * in which the callbacks will be stored.
     *
     * @access public
     */
    
    
    function __construct() {
        $this->insert_id = 0;
        $this->callbacks = array();
    }



    /**
     * ::add_callback( callback $reference [, array $arguments ] )
     *
     * Creates a new callback object from a function or method reference and (if specified) the
     * arguments. This object will be stored into the hook's callbacks array.
     *
     * @param callback A reference to a function or a method.
     * @param array List of arguments to use when the reference is called.
     * @access public
     */

         
    function add_callback($reference, $arguments = array() ) {
        $callback = new Callback($reference, $arguments);
        $this->callbacks[$this->insert_id++] = $callback;
    }



    /**
     * ::get_callback( int $id )
     *
     * Use this method to get a stored callback object by id. The callback object will
     * contain the same arguments as it was stored with.
     *
     * @param int The id of the callback.
     * @return object The callback object created when it was stored.
     * @access public
     */
    
    
    function get_callback($id) {
        if( !isset($this->callbacks[$id]) )
            return false;
        
        return $this->callbacks[$id];
    }

    

    /**
     * ::unset_callback( int $id )
     *
     * Deletes and deletes an object from the list.
     *
     * @param int The id of the callback to delete.
     * @access public
     */
        
    
    function unset_callback($id) {
        unset($this->callbacks[$id]);
    }



    /**
     * ::trigger( [array $args] )
     *
     * Executes all stored callbacks. The optional parameter is used to pass extra arguments to the callbacks
     * when they are called. These arguments will be appended to the arguments specified when the callback
     * was added to the hook.
     *
     * @param array Extra arguments to pass to the callbacks.
     * @access public
     */
    
    
    function trigger( $args = array() ) {
        foreach($this->callbacks as $callback) {
            $callback->call($args);
        }        
    }



    /**
     * ::apply( mixed $subject )
     *
     * A slight different from the trigger method, in this case all the callbacks will change the value
     * of the specified subject. In order to use this correctly it is important that all the stored callbacks
     * will return their last parameter and that this parameter isn't specified when they are added.
     *
     * @param mixed The subject to apply the results of the callbacks on.
     * @return mixed The result of applying all the callback to the subject.
     * @access public
     */

    
    function apply( $subject ) {
        foreach($this->callbacks as $callback) {
            $subject = $callback->call( array($subject) );
        }

        return $subject;        
    }

}



?>



--- class.callback.php ---

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
/**
 * PHP Class - Callback
 *
 * This simple class can be used to ease dealing with callbacks in applications. Creating a new instance is actually creating a shortcut to
 * a callback with certain specified parameters. The main target of this class is to separate application logic from callback handling, think
 * of the repeated return of if/ else conditions, callback validation etc.
 * So it is important to only use this class when it clearly has an advantage over dealing with functions and methods the way it is done usually,
 * and NOT as just a shortcut for a function or method.
 *
 * @author Emiel Klein Ovink
 * @link http://www.kleinovink.net, http://www.sparkle6.com
 * @copyright 2008
 */




class Callback {


    private $reference; // Reference to a valid callback
    private $arguments;    // Arguments that will be passed to the reference.
    private $num_calls; // The amount of times callback object has been called.



    /**
     * ::__construct( callback $reference [, array $arguments ] )
     *
     * Validates the callback reference specified in the first parameter and initializes the properties of the
     * object. The optional second parameter can contain an array with arguments which will be passed when the
     * callback is called. Invalid callbacks references will cancel the constructor and trigger an error.
     *
     * @param callback Reference to a valid callback
     * @param array The arguments to pass to the callback.
     * @access public
     */
    
         
    public function __construct( $reference , $arguments = array() ) {
        if( !is_callable($reference) ) {
            trigger_error("The specified reference is not a valid callback reference." ,    E_USER_WARNING );
            return;
        }

        $this->reference = $reference;
        $this->arguments = $arguments;
        $this->num_calls = 0;
    }



    /**
     * ::call( [, array $args ] )
     *
     * Calls the callback reference and passes the objects arguments to it. The optional parameter can be
     * used to append any extra arguments to the callback.
     *
     * @param array Extra arguments to pass to the callback.
     * @access public
     */
    
    
    public function call( $args = array() ) {                
        $args = (empty($args)) ? $this->arguments : array_merge($this->arguments, $args);
        $this->num_calls++;
        
        return call_user_func_array($this->reference, $args);    
    }



    /**
     * ::num_calls( void )
     *
     * @return The amount of times the method call() has been called.
     * @access public
     */
    
    
    public function num_calls() {
        return $this->num_calls;
    }


    /**
     * ::num_args( void )
     *
     * @return The number of arguments stored in the object
     * @access public
     */
    
    
    public function num_args() {
        return count($this->arguments);
    }


    /**
     * ::get_args( void )
     *
     * @return The array with arguments stored in the object
     * @access public
     */
    
    
    public function get_args() {
        return $this->arguments;
    }


    /**
     * ::get_ref( void )
     *
     * @return The reference to a callback
     * @access public
     */
    
         
    public function get_ref() {
        return $this->reference;
    }

}


?>



Het voorbeeld

Een voorbeeldje waarin errors worden afgehandeld. Nou ben ik zelf van mening dat het niet het meest tot zijn recht komt op deze manier, maar het was een eenvoudige manier om de functionaliteit te illustreren.

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

include 'class.hook.php';
include 'class.callback.php';


// Functie voor het afhandelen van fouten, in dit geval wordt het error event getriggered
function error_handler($errno, $errstr, $errfile, $errline, $errcontext ) {
    global $error_event;
    $args = array($errno, $errstr, $errfile, $errline, $errcontext);
    $error_event->trigger($args);
}


// Deze functies gaan we hangen aan het error event
function print_error($prefix, $errno, $errstr) {
    print $prefix;
    print "\n".$errno.' - '.$errstr;
}

function
mail_error( $errno, $errstr ) {
    $subject = 'Error '.$errno;
    mail('[email protected]', $subject, $errstr );
}


// We maken een nieuwe instance van Hook en noemen die $error_event
$error_event = new Hook();

$error_event->add_callback('print_error', array('Er is een error') );
$error_event->add_callback('mail_error');

// Error handler opgeven...
set_error_handler('error_handler', error_reporting() );


// In dit bestand worden dingen veranderd aan de hook.
// Bijvoorbeeld print_error verwijderen, extra functies er aan hangen, noem maar op.
// Je kunt zo natuurlijk bestanden includen onder allerlei voorwaarden.

if( file_exists('advanced-error.php') ) {
    include 'advanced-error.php';
}



trigger_error('Deze error wordt anders afgehandeld wanneer de include het error event veranderd');

/*
Indien $error_event onveranderd wordt het volgende geprint:

Er is een error
1024 - Deze error wordt anders afgehandeld wanneer de include de error hook veranderd

en wordt er een mailtje verstuurd....

*/


?>

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.