Sokil\Mongo\Document::attachBehavior PHP Method

attachBehavior() public method

public attachBehavior ( string $name, string | array | Sokil\Mongo\Behavior $behavior ) : Document
$name string unique name of attached behavior
$behavior string | array | Sokil\Mongo\Behavior Behavior instance or behavior definition
return Document
    public function attachBehavior($name, $behavior)
    {
        if (is_string($behavior)) {
            // behavior defined as string
            $className = $behavior;
            $behavior = new $className();
        } elseif (is_array($behavior)) {
            // behavior defined as array
            if (empty($behavior['class'])) {
                throw new Exception('Behavior class not specified');
            }
            $className = $behavior['class'];
            unset($behavior['class']);
            $behavior = new $className($behavior);
        } elseif (!$behavior instanceof Behavior) {
            // behavior bust be Behavior instance, but something else found
            throw new Exception('Wrong behavior specified with name ' . $name);
        }
        $behavior->setOwner($this);
        $this->behaviors[$name] = $behavior;
        return $this;
    }