Laravel 5:未找到事件 class 命名空间/class

Laravel 5: Event class namespacing / class not found

这更像是一个 PHP 命名空间问题,而不是 Laravel 问题。我正在 Laravel 中创建我的第一个事件和处理程序。我非常仔细地遵循手册,以及 this nice blog post

我的 EventServiceProvider.php 脚本包括:

/**
 * The event handler mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'event.name' => [
        'EventListener'
    ],
    'App\Events\LeadSignup' => [
        'App\Handlers\Events\SendLeadNotification',
    ],  
];

我不确定这是否正确,但它似乎有效。我创建了 /app/Handlers/Events/SendLeadNotification.php 文件,其中包含:

<?php namespace App\Handlers\Events;

use App\Events\LeadSignup;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;

class SendLeadNotification {

    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  LeadSignup  $event
     * @return void
     */
    public function handle(LeadSignup $event)
    {
        print("handling it");
        print_r($event);
        exit(0);
    }

}

此外,我的/app/Events/LeadSignup.php事件代码是:

<?php namespace App\Events;

use App\Events\Event;

use Illuminate\Queue\SerializesModels;

class LeadSignup extends Event {

    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

}

我的事件触发代码:

\Event::fire(new LeadSignup($lead));

但这导致了一个错误:

Class App\Http\Controllers\Site\LeadSignup not found

我最终能够通过明确说明 LeadSignup 的位置来修复它 class:

\Event::fire(new \App\Events\LeadSignup($lead));

我的问题是:我怎样才能使代码更漂亮,就像在 Laravel 文档中那样,我可以在其中简单地调用:

\Event::fire(new LeadSignup($lead));

?或者,换句话说,如何将 LeadSignup class 添加到我的全局命名空间? (如果我用错了术语,我深表歉意。)

已解决!

lpeharda 的回答对我有用。我在我的控制器代码中触发事件:

\Event::fire(new LeadSignup($lead));

一旦我添加

use App\Events\LeadSignup

.. 在我的控制器代码中,可以找到 class。这是我的完整控制器代码,您可以看到它的实际效果:

<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Events\LeadSignup; // <=== here's the additional code

class LeadsController extends Controller {

    public function __construct()
    {
        parent::__construct();      
    }

    public function postInsert()
    {
        if(! \Lead::where('email', '=', \Request::input('email'))->exists()) 
        {
           $lead = \Lead::create(\Request::all());
           \Event::fire(new LeadSignup($lead));
        }
    }

}

?>

在您调用的文件中

\Event::fire(new LeadSignup($lead));

您需要 add/use LeadSignup 事件的命名空间。

例如,在该文件的顶部添加

use App\Events\LeadSignup

就在开始 PHP 标记下方(以及最终命名空间声明下方):

<?php

希望这对您有所帮助。

如果没有,请告诉我你从哪里打电话给

Event::fire()

立面,我可以精确定位。