Heim  >  Artikel  >  Backend-Entwicklung  >  详解在PHP的Yii框架中使用行为Behaviors的方法_php技巧

详解在PHP的Yii框架中使用行为Behaviors的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 19:56:26959Durchsuche

一个绑定了行为的类,表现起来是这样的:

// Step 1: 定义一个将绑定行为的类
class MyClass extends yii\base\Component
{
  // 空的
}

// Step 2: 定义一个行为类,他将绑定到MyClass上
class MyBehavior extends yii\base\Behavior
{
  // 行为的一个属性
  public $property1 = 'This is property in MyBehavior.';

  // 行为的一个方法
  public function method1()
  {
    return 'Method in MyBehavior is called.';
  }
}

$myClass = new MyClass();
$myBehavior = new MyBehavior();

// Step 3: 将行为绑定到类上
$myClass->attachBehavior('myBehavior', $myBehavior);

// Step 4: 访问行为中的属性和方法,就和访问类自身的属性和方法一样
echo $myClass->property1;
echo $myClass->method1();

上面的代码你不用全都看懂,虽然你可能已经用脚趾头猜到了这些代码的意思, 但这里你只需要记住行为中的属性和方法可以被所绑定的类像访问自身的属性和方法一样直接访问就OK了。 代码中, $myClass 是没有 property1 method() 成员的。这俩是 $myBehavior 的成员。 但是,通过 attachBehavior() 将行为绑定到对象之后, $myCalss 就好像练成了吸星大法、化功大法,表现的财大气粗,将别人的属性和方法都变成了自己的。

另外,从上面的代码中,你还要掌握使用行为的大致流程:

  • 从 yii\base\Component 派生自己的类,以便使用行为;
  • 从 yii\base\Behavior 派生自己的行为类,里面定义行为涉及到的属性、方法;
  • 将Component和Behavior绑定起来;
  • 像使用Component自身的属性和方法一样,尽情使用行为中定义的属性和方法。

使用行为,必须像前文描述的一样先把它附加到 yii\base\Component 类或其子类。一旦行为附加到组件,就可以直接使用它。

行为附加到组件后,可以通过组件访问一个行为的公共成员变量或 getter 和 setter 方法定义的属性:

// "prop1" 是定义在行为类的属性
echo $component->prop1;
$component->prop1 = $value;
类似地也可以调用行为的公共方法:

// foo() 是定义在行为类的公共方法
$component->foo();

如你所见,尽管 $component 未定义 prop1 和 foo() ,它们用起来也像组件自己定义的一样。

如果两个行为都定义了一样的属性或方法,并且它们都附加到同一个组件,那么首先附加上的行为在属性或方法被访问时有优先权。

附加行为到组件时的命名行为,可以使用这个名称来访问行为对象,如下所示:

$behavior = $component->getBehavior('myBehavior');

也能获取附加到这个组件的所有行为:

$behaviors = $component->getBehaviors();

移除行为

要移除行为,可以调用 yii\base\Component::detachBehavior() 方法用行为相关联的名字实现:

$component->detachBehavior('myBehavior1');

也可以移除全部行为:

$component->detachBehaviors();

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn