Yii2: multiple event attach on view

2019-05-13 17:08发布

问题:

Hi,
I want try to make some dynamic sidebar and content, I have trigger event multiple times in view,
here my code:

backend/view/layouts/_sidebar.php

use common\component\Hook;
use yii\base\Event;

Event::trigger(Hook::className(), Hook::SIDEBAR_MENU);

backend/view/ext/index.php

use common\component\Hook;
use yii\base\Event;

Event::trigger(Hook::className(), Hook::PlUGIN_CONTENT);

common/component/Hook.php

namespace common\component;

use yii\base\Component;

class Hook extends Component{

    const SIDEBAR_MENU = '';
    const PlUGIN_CONTENT = '';

}

backend\plugins\Plugin\index.php

namespace backend\plugins\Plugin;

use Yii;
use common\component\Hook;
use yii\base\Event;
use yii\helpers\Html;

class Index extends Event{
    function sidebar() {
        echo '<li>' . Html::a('Menu Plugin 1', ['/ext?n=Plugin']) . '</li>';
    }

    function renderContent(){
        echo 'this is content';
    }
}

Event::on(Hook::className(), Hook::SIDEBAR_MENU, [new Index, 'sidebar']);
Event::on(Hook::className(), Hook::PlUGIN_CONTENT, [new Index, 'renderContent']);

backend\plugins\Plugin2\index.php

namespace backend\plugins\Plugin2;

use Yii;
use common\component\Hook;
use yii\base\Event;
use yii\helpers\Html;

Event::on(Hook::className(), Hook::SIDEBAR_MENU, function () {
    echo '<li>' . Html::a('Menu Plugin 2', ['/ext?n=Plugin2']) . '</li>';
});

and here my controller backend/controller/ExtController.php

namespace backend\controllers;

use Yii;
use yii\web\Controller;

class ExtController extends Controller
{
    public function actionIndex(){    
        return $this->render('index');
    }

}

question:

  1. why they appear multiple times in _sidebar.php?, I am just trigger SIDEBAR MENU in sidebar.php, why they trigger SIDEBAR_MENU and PLUGIN_CONTENT in same times?
  2. I have trigger event too in in backend/view/ext/index.php, but PLUGIN_CONTENT not triggered, so the content doesn't appear

回答1:

in hook.php, they both have same value, which is empty string "", they mush have value

namespace common\component;

use yii\base\Component;

class Hook extends Component{

    const SIDEBAR_MENU = 'sidebarMenu';
    const PlUGIN_CONTENT = 'pluginContent';

}


标签: php events yii2