PHP code example of ikkez / f3-events

1. Go to this page and download the library: Download ikkez/f3-events library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ikkez / f3-events example snippets


// fetch the global Event instance
$events = \Sugar\Event::instance();

// typical F3 callstring
$events->on('user_login', 'Notification->user_login');
// or with callbacks
$events->on('user_login', function(){
  // ...
});
// or with callables
$events->on('user_login', [$this,'method']); 

$events->emit('user_login');

$events->on('user_login', function($username){
  \Logger::log($username.' logged in');
});
$events->emit('user_login', 'freakazoid');

$events->on('user_login', function($username){
  \Logger::log($username.' logged in');
}, 10); // 10 is default priority
$events->on('user_login', function(){
  \Flash::addMessage('You have logged in successfully');
}, 20); // 20 is a higher priority and is called first
$events->emit('user_login', 'freakazoid');

$events->on('user_login', function($username){
  \Logger::log($username.' logged in');
});
$events->on('user_login', function(){
  \Flash::addMessage('You have logged in successfully');
  return false; // <-- skip any other listener on the same event
}, 20);
$events->emit('user_login', 'freakazoid');
// The logger event isn't called anymore

$events->on('user_login', function($username,$context){
  if ($context['lang'] == 'en')
    \Flash::addMessage('You have logged in successfully');
  elseif($context['lang'] == 'de')
    \Flash::addMessage('Du hast dich erfolgreich angemeldet');
});
$events->emit('user_login', 'freakazoid', array('lang'=>'en'));

$events->on('user_login', function($username,$context,$event){
  \Flash::addMessage('You have logged in successfully', $event['options']['type']);
}, 20, array('type'=>'success'));

$events->on('get_total', function($basket){
  $sum = 0;
  foreach($basket as $prod) {
    $sum+=$prod;
  }
  return $sum;
});

$products = array(
  'a' => 2,
  'b' => 8,
  'c' => 15,
);

$sum = $events->emit('get_total',$products);
echo $sum; // 25

$events->on('get_total.tax', function($sum){
  return $sum+($sum*0.2);
});
$events->on('get_total.shipping', function($sum){
  return $sum+5;
});
$sum = $events->emit('get_total',$products);
echo $sum; // 35

$events->off('get_total.tax');
$sum = $events->emit('get_total',$products);
echo $sum; // 30

$user = new \Model\User();
$events->watch($user)->on('update.email','\Mailer->sendEmailActivationLink');

// Event Tests
$f3->concat('AUTOLOAD', ',path/to/f3-events/test/');
\Sugar\EventTests::init();