Extending

Let's extend our "Hello World!" worklet from the previous article. Here's the situation: script shouldn't print "Hello World!" when "mood" parameter of Base module is set to ":(" and it should print "Hello World!!!" when "mood" is set to ":)".

Act "before" task

In order to prevent taskHello from printing we need to act before it happens. So we need to create behavior with "beforeTaskName" method: beforeHello in our case.

Create behavior in /protected/modules/custom/behaviors/BCustomHello.php:

class BCustomHello extends UWorkletBehavior
{
    public function beforeHello()
    {
        if( $this->owner->param('mood') == ':(' )
            return false;
    }
}

"Before" methods can be used to do something before the actual call to the task and if such method returns anything except null further execution of the task cancels. In our example we return false to prevent taskHello from even being called.

Act "after" task

Now we need to append "Hello World!" with 2 extra exclamation marks if the mood is good. We'll use the same behavior file, but this time we will add afterHello method.

class BCustomHello extends UWorkletBehavior
{
    public function beforeHello()
    {
        if( $this->owner->param('mood') == ':(' )
            return false;
    }
 
    public function afterHello($currentResult)
    {
        if( $this->owner->param('mood') == ':)' )
            return $currentResult . '!!';
    }
}

Notice how "after" method always receives one extra argument (comparing to master task method) which holds task execution result up to this moment.

$currentResult = whatever has been currently returned by taskHello + any other afterHello methods which have been called earlier.

"After" methods can be used to do something after the actual call to the task and to alter the overall task execution result.

Filter

We've got a worklet - WBaseHello - and behavior - BCustomHello - but they are not linked to each other yet. We need to create a worklet filter in /protected/modules/custom/filters/FCustomMain.php

class FCustomMain
{
    public function filters()
    {
        return array(
            'base.hello' => array('behaviors' => array('custom.hello')),
        );
    }
}

Finally we should tell Base module that there's a filter for it. We need to add it to the /protected/config/public/modules.php

<?php
return array (
  'modules' => 
  array (
  ...
    'base' => 
    array (
      'params' => 
      array (
        ...
      ),
      'filters' => 
      array (
        'custom.main' => true,
      ),
    ),
  ...
  ),
);

So here's the magic. Now if we call

wm()->get('base.hello')->hello();

it will return null if "mood" is bad, "Hello World!" if "mood" is not set and "Hello World!!!" if "mood" is good!