Yii: What is signature of behaviors?

110 Views Asked by At

what is signature of behaviors in yii? should this be a function or a class method? Can any provide sample code?

1

There are 1 best solutions below

0
AudioBubble On BEST ANSWER

There is no signature for behaviors, as behaviors are intented to add some function to class. Only requirement is to extend from CBehavior. Like in wiki or docs:

class SomeClass extends CBehavior
{
    public function add($x, $y) { return $x + $y; }
}

class Test extends CComponent
{
    public $blah;
}

$test = new Test(); 
// Attach behavior
$test->attachbehavior('blah', new SomeClass);

// Now you can call `add` on class Test
$test->add(2, 5);

However since PHP 5.4 you can use Traits which are native php implementation and have a lot more features, example above with traits:

// NOTE: No need to extend from any base class
trait SomeClass
{
    public function add($x, $y) { return $x + $y; }
}

class Test extends CComponent
{
    // Will additionally use methods and properties from SomeClass
    use SomeClass;
    public $blah;
}

$test = new Test(); 
// You can call `add` on class Test because of `use SomeClass;`
$test->add(2, 5);

There are a lot more features with traits