2014-03-25 79 views
4

我正在嘗試向服務提供者註冊事件,但我不斷收到反射類錯誤。我已經搜索並找不到解決方案,或許這是核心問題。Laravel 4.1。*問題註冊服務提供商中的事件

// AppServiceProvider.php 

<?php namespace App; 

use Illuminate\Support\ServiceProvider; 
use App\Events\UserEventHandler; 

class AppServiceProvider extends ServiceProvider { 

    public function register() { 

     // Events 
     $this->app->events->subscribe(new UserEventHandler); 

    } 

} 

// UserEventHandler.php 

<?php namespace App\Events; 

class UserEventHandler { 

/** 
* Handle user login events. 
*/ 
public function onUserLogin($event) 
{ 
    echo 'subscriber logged in'; exit; 
} 

/** 
* Register the listeners for the subscriber. 
* 
* @param Illuminate\Events\Dispatcher $events 
* @return array 
*/ 
public function subscribe($events) 
{ 
    $events->listen('auth.login', '[email protected]'); 
} 

} 

$this->app->events->subscribe(new UserEventHandler);被燒成很好,因爲我可以到達訂閱方法,但是$events->listen('auth.login', '[email protected]');將返回一個異常Class UserEventHandler does not exist

我曾嘗試在global.php相同的代碼和工作正常,那麼問題就出在ServiceProvider,我已經嘗試了register()和boot()兩種方法,並得到相同的錯誤。

[增訂]

我發現,你需要明確指定完整的命名空間監聽事件時。

public function subscribe($events) 
{ 
    $events->listen('auth.login', 'App\Events\[email protected]'); 
} 
+0

在添加類之後,你有'composer-dump'嗎? –

+0

是的,我已經嘗試過所有的作曲家轉儲自動加載,PHP的工匠轉儲自動加載和什麼都沒有,類確實存在,並且確實實例化,就像我說我可以達到訂閱的方法,但是不通過'$ events- > listen('auth.login','UserEventHandler @ onUserLogin');' –

+0

經過數小時的沮喪之後,我發現您需要專門指定字符串上的完整名稱空間才能工作。 '$ events-> listen('auth.login','App \ Events \ UserEventHandler @ onUserLogin');' –

回答

5

如果需要聲明該類的完整路徑(如果它位於與服務提供者不同的目錄中)。

+0

謝謝@philipbrown我已經解決了這個問題,謝謝你:) –