mardi 1 août 2017

Laravel 5.2 - How to access an App Presenter method in EventServiceProvider?

I have a guitar lessons site where there is an exercises table. The original developers placed some functions in ExercisePresenter to retrieve other bits of data associated with an exercise, such as its url.

Here is a function in ExercisePresenter that returns url for an exercise:

public function url()
{
    return '/guitar-lesson-ex/' . $this->urlName() . '/' . $this->id;
}

So now I am creating an event on new exercise created so I can use pusher notifications. In the EventServiceProvider I have this:

public function boot(DispatcherContract $events)
{
    parent::boot($events);

    Exercise::created(function ($exercise) {
        // need to update lesson difficulty
        $lesid = $exercise->lesson_id;
        $les = \App\Lesson::find($lesid);
        $dif = $les->difficulty();
        DB::table('lessons')
            ->where('id', $lesid)
            ->update(['difficulty' => $dif]);

        // lets trigger NewExerciseEvent to send pusher notifications
        $url = $exercise->url;
        event(new NewExerciseEvent($message));
    });
}

I thought in above code $url = $exercise->url; would work since I see $exercise->url used successfully in exercise views. But it is returning $url as null. Now, there is no url column in the exercise database, so I figure somehow when $exercise->url; is used in a view, laravel is figuring out that the ExercisePresenter is able to return the url.

I am debugging through PHPStorm, but when I get to $url = $exercise->url; and step in, I am just taken through various bits of laravel code that looks for a method, etc. I am not savvy enough with laravel to figure out what it is doing here differently than in the view (too bad we can't debug views...), but each time I try this $url is returned as null.

Any idea how to get this to work properly in my EventServiceProvider?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire