(1)类,这里的类最起码要继承\yii\base\Component类,这里\yii\db\ActiveRecord也是继承了\yii\base\Component类的子类
//app/models/Country
namespace app\models;
use Yii;
use app\components\MyBehavior;
class Country extends \yii\db\ActiveRecord
{
const EVENT_XF = 'event-xf';
/**
*
*/
public function __construct()
{
$this->on(self::EVENT_XF, ['app\Components\MyEvent', 'eventxf'],'hi!!!');
}
/**
* @return array
*/
public function behaviors()
{
return [
'myBehavior' => MyBehavior::className(),
];
}
// /**
// * @inheritdoc
// */
// public static function tableName()
// {
// return 'country';
// }
//
// /**
// * @inheritdoc
// */
// public function rules()
// {
// return [
// [['code', 'name'], 'required'],
// [['population'], 'integer'],
// [['code'], 'string', 'max' => 2],
// [['name'], 'string', 'max' => 52],
// [['code'], 'unique'],
// ];
// }
//
// /**
// * @inheritdoc
// */
// public function attributeLabels()
// {
// return [
// 'code' => 'Code',
// 'name' => 'Name',
// 'population' => 'Population',
// ];
// }
}
(2.1)行为
//app/components/MyBehavior
namespace app\components;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
class MyBehavior extends Behavior
{
// 行为的一个属性
public $property1 = 'This is property in MyBehavior.';
// 行为的一个方法
public function method1()
{
return 'Method in MyBehavior is called.';
}
// 重载events() 使得在事件触发时,调用行为中的一些方法
public function events()
{
// 在EVENT_BEFORE_VALIDATE事件触发时,调用成员函数 beforeValidate
return [
ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
];
}
// 注意beforeValidate 是行为的成员函数,而不是绑定的类的成员函数。
// 还要注意,这个函数的签名,要满足事件handler的要求。
public function beforeValidate(Event $event)
{
var_dump($event);
// debug_print_backtrace();
echo $event->sender.'自定义行为里的触发事件,行为里的事件无法传data内容', PHP_EOL;
}
}
(2.2)事件
//app/components/MyEvent
namespace app\components;
use yii\base\Event;
class MyEvent
{
static public function eventxf (Event $event) {
echo $event->sender. '的自定义事件,事件内容是:'.$event->data, PHP_EOL;
}
}
(3)commands里调用
//app/commands/TestController
namespace app\commands;
use yii\base\Event;
use yii\console\Controller;
use yii\db\ActiveRecord;
use yii\di\Container;
use app\models\Country;
class TestController extends Controller
{
public function actionTest1()
{ //行为中的事件触发
$country = new Country();
$event = new Event();
$event->sender = 'wuhuaguo';
echo $country->property1, PHP_EOL;
echo $country->method1(), PHP_EOL;
$country->trigger(ActiveRecord::EVENT_BEFORE_VALIDATE, $event);
}
public function actionTest2()
{ //行为中的事件触发
$country = new Country();
$event = new Event();
$event->sender = 'wuhuaguo2';
$country->trigger(Country::EVENT_XF, $event);
}
}