"Hello World!"

Let's create a simple worklet in a Base module.

We need to create the following file: /protected/modules/base/worklets/WBaseHello.php

Now let's put the code inside:

<?php
class WBaseHello extends USystemWorklet
{
    public function taskHello()
    {
        return 'Hello World!';
    }
}

If you want any method of your worklet to be available for dynamic extension prepend its name with 'task'. Now anywhere in our application we can call:

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

and it will print "Hello World!". wm() is just a shortcut for Yii::app()->workletManager component.

Use as Action or Widget

In the above example base.hello worklet is being used as a helper class. It has a method "hello" which is being called from other parts of the code.

Now let's turn it into an action so that if you load http://yourdomain.com/base/hello it will print our "Hello World!" text.

<?php
class WBaseHello extends UWidgetWorklet
{
    public function taskRenderOutput()
    {
        echo 'Hello World!';
    }
}
  1. We have replaced UWorklet with UWidgetWorklet as WBaseHello parent class because only widget worklets can act as actions.
  2. We have renamed taskHello with taskRenderOutput - that's a default name of the task that prints output of a widget worklet.

Furthermore our base.hello worklet can now be used as a widget:

echo app()->controller->worklet('base.hello');

will print "Hello World!" anywhere we call it (read more).