今天看了symfony中event章節(jié),自己也動手做了個實驗,但是有一個地方不是很明白。
我首先定義了一個Eents的枚舉類別用於管理所有的event
<?php
namespace Wolehao\HomeBundle\Event;
final class Events{
const HOMEPAGE_VISIT = "home.homepage_visit";
}
在HomepageBundle定義了一個event
<?php
namespace Wolehao\HomeBundle\Event;
// 這個是sf為你提供的一個基礎(chǔ)類
use Symfony\Component\EventDispatcher\Event;
// 你的事件類
class HomepageVisit extends Event {
public $container;
public function __construct($container) {
$this->container = $container;
}
}
然後在FileBundle中定義了一個listener
<?php
namespace Wolehao\FileBundle\EventListener;
use Wolehao\HomeBundle\Event\HomepageVisit;
class FileListener
{
public function onHomepageVisit(HomepageVisit $event)
{
$event->container->get("logger")->info("我執(zhí)行了");
// ...
}
}
在service.xml中註冊服務(wù)
<services>
<service id="file.listener" class="Wolehao\FileBundle\EventListener\FileListener">
<tag name="kernel.event_listener" event="home.homepage_visit" method="onHomepageVisit"/>
</service>
</services>
最後我在HomepageBundle的controller中觸發(fā)事件
<?php
namespace Wolehao\HomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Wolehao\HomeBundle\Event\HomepageVisit;
use Wolehao\HomeBundle\Event\Events;
use Wolehao\FileBundle\Event\Listener;
class DefaultController extends Controller
{
/**
* @Route("/home/{name}")
* @Template()
*/
public function indexAction($name)
{
$event = new HomepageVisit($this->container);
// 在controller里取事件分發(fā)器
$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch(Events::HOMEPAGE_VISIT, $event);
return array('name' => $name);
}
}
先在我透過http://localhost/fm/web/app_dev.php/home/index訪問
能夠正確的列印出"我執(zhí)行了"的日誌
一切好像都沒有問題,說明事件成功被觸發(fā)執(zhí)行
現(xiàn)在透過點擊debug bar,的event項如下面所示:
我不懂的是為什麼home.homepage_visit在Not Called Listeners裡面,但明明執(zhí)行了的啊?
歡迎選擇我的課程,讓我們一起見證您的進步~~
你的symfony 2的具體版本?
如果確實寫了log,表示你的event相關(guān)程式碼是有效的。
profiler(debug bar)裡顯示的信息,是透過data collector收集來的,至於為什麼沒有記錄到listener的調(diào)用,則需要知道更多細節(jié)才能了解,建議你詳細檢查xdebug token和profiler信息的對應(yīng)關(guān)係。
另外,不要直接注入container給event,這樣依賴過於寬泛了。