목차
Setting the stage#
Introducing Event Annotations#
Conclusion#
php教程 php手册 Laravel 5.0 – Event Annotations

Laravel 5.0 – Event Annotations

Jun 06, 2016 pm 08:13 PM
event laravel

原文 ? http://mattstauffer.co/blog/laravel-5.0-event-annotations Posted on October 10, 2014 | By Matt Stauffer (This is part of a series of posts on New Features in Laravel 5.0. Check back soon for more.) Laravel 5.0 Form Requests Laravel

Posted on October 10, 2014 | By Matt Stauffer

(This is part of a series of posts on New Features in Laravel 5.0. Check back soon for more.)

  1. Laravel 5.0 – Form Requests
  2. Laravel 5.0 – ValidatesWhenResolved
  3. Laravel 5.0 – Directory structure and namespace
  4. Laravel 5.0 – Route Caching
  5. Laravel 5.0 – Cloud File Drivers
  6. Laravel 5.0 – Method Injection
  7. Laravel 5.0 – Route Annotations
  8. Laravel 5.0 – Event Annotations
  9. Laravel 5.0 – Middleware (and how it’s replacing Filters) (coming soon)

In 5.0, Laravel is moving more and more of the top-level, bootstrapped, procedural bindings and definitions into a more Object-Oriented, separation-of-concerns-minded structure. Filters are now objects, controllers are now namespaced, the PSR-4-loaded application logic is now separate from the framework configuration, and more.

We saw in thelast postthat annotations are one of the ways Laravel 5.0 is making this change. Where routes used to be bound one after another in routes.php, they now can be bound with annotations on the controller class and method definitions.

Setting the stage#

Another part of Laravel that has traditionally been bound with a list of calls one after another is event listeners, and this is the next target of the annotation syntax.

Consider the following code:

Event::listen('user.signup', function($user)
{
    $intercom = App::make('intercom');
    $intercom->addUser($user);
});
로그인 후 복사

Somewhere in your code—in a service provider, maybe, or maybe just in a global file somewhere—you’ve bound a listener (the closure above) to the “user.signup” event.

Of course, you’re probably noticing that all that closure does is call a single method—so we could refactor it to this:

Event::listen('user.signup', 'Intercom@addUser');
로그인 후 복사

Introducing Event Annotations#

Now, let’s drop the need for the binding entirely, and replace it with an annotation.

<?php namespace App;
class Intercom
{
  /**
   * @Hears("user.signup")
   */
  public function addUser(User $user)
  {
    return $this->api_wrapper->sendSomeAddThing(
      $user->email,
      $user->name
    );
  }
}
로그인 후 복사

As you can see, the @Hears annotation can take a string event name, but it can also take an array of event names (in annotations, arrays are surrounded by {} instead of []). Now, run artisan event:scan and you’ll get a file namedstorage/framework/events.scanned.php , with the following contents:

<?php $events->listen(array (
  0 => 'user.signup',
), 'App\Intercom@addUser');
로그인 후 복사

Instantly bound.

Conclusion#

There are positives and negatives to working with your event system this way.

The primary negative I see is that you could look at this annotation as being framework-specific; if that’s the case, you’re now placing framework-specific code directly into your domain. If you imagine this Intercom class being something you’re passing around between several sites, its binding may be specific to this site–in which case you’d be better off using the classic style of binding. However, that’s not always the case.

Note that this negative is different from the same situation in Route Annotations, which are only being applied to Controllers–which are not domain objects.

The positives I can see at first glance are that first, you’re defining the method’s act of listening on the method itself, rather than elsewhere; and second, that you’re defining the listener in a way that it can be programmatically accessed (meaning you could, at any point, replace artisan event:scan with a program of your own devising that outputs something other than a Laravel events.scanned file). There are likely smarter folks than me that’ll weigh in on this.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Laravel - 장인 명령 Laravel - 장인 명령 Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7은 새로운 명령을 처리하고 테스트하는 새로운 방법을 제공합니다. 여기에는 장인 명령을 테스트하는 새로운 기능이 포함되어 있으며 데모는 아래에 언급되어 있습니다.

Laravel - 페이지 매김 사용자 정의 Laravel - 페이지 매김 사용자 정의 Aug 27, 2024 am 10:51 AM

Laravel - 페이지 매김 사용자 정의 - Laravel에는 사용자나 개발자가 페이지 매김 기능을 포함하는 데 도움이 되는 페이지 매김 기능이 포함되어 있습니다. Laravel 페이지네이터는 쿼리 빌더 및 Eloquent ORM과 통합되어 있습니다. 자동 페이지 매김 방법

Laravel에서 이메일 전송이 실패 할 때 반환 코드를 얻는 방법은 무엇입니까? Laravel에서 이메일 전송이 실패 할 때 반환 코드를 얻는 방법은 무엇입니까? Apr 01, 2025 pm 02:45 PM

Laravel 이메일 전송이 실패 할 때 반환 코드를 얻는 방법. Laravel을 사용하여 응용 프로그램을 개발할 때 종종 확인 코드를 보내야하는 상황이 발생합니다. 그리고 실제로 ...

laravel 일정 작업이 실행되지 않습니다 : 스케줄 후 작업이 실행되지 않으면 어떻게해야합니까? laravel 일정 작업이 실행되지 않습니다 : 스케줄 후 작업이 실행되지 않으면 어떻게해야합니까? Mar 31, 2025 pm 11:24 PM

laravel 일정 작업 실행 비 응답 문제 해결 Laravel의 일정 작업 일정을 사용할 때 많은 개발자 가이 문제에 직면합니다 : 스케줄 : 실행 ...

Laravel에서는 이메일로 확인 코드를 보내지 못하는 상황을 처리하는 방법은 무엇입니까? Laravel에서는 이메일로 확인 코드를 보내지 못하는 상황을 처리하는 방법은 무엇입니까? Mar 31, 2025 pm 11:48 PM

Laravel의 이메일을 처리하지 않는 방법은 LaRavel을 사용하는 것입니다.

DCAT 관리자에서 데이터를 추가하기 위해 클릭하는 사용자 정의 테이블 기능을 구현하는 방법은 무엇입니까? DCAT 관리자에서 데이터를 추가하기 위해 클릭하는 사용자 정의 테이블 기능을 구현하는 방법은 무엇입니까? Apr 01, 2025 am 07:09 AM

DCAT를 사용할 때 DCATADMIN (LARAVEL-ADMIN)에서 데이터를 추가하려면 사용자 정의의 테이블 기능을 구현하는 방법 ...

Laravel Redis Connection 공유 : 선택 메소드가 다른 연결에 영향을 미치는 이유는 무엇입니까? Laravel Redis Connection 공유 : 선택 메소드가 다른 연결에 영향을 미치는 이유는 무엇입니까? Apr 01, 2025 am 07:45 AM

Laravel 프레임 워크 및 Laravel 프레임 워크 및 Redis를 사용할 때 Redis 연결을 공유하는 데 영향을 줄 수 있습니다. 개발자는 문제가 발생할 수 있습니다. 구성을 통해 ...

Laravel - 덤프 서버 Laravel - 덤프 서버 Aug 27, 2024 am 10:51 AM

Laravel - 덤프 서버 - Laravel 덤프 서버는 Laravel 5.7 버전과 함께 제공됩니다. 이전 버전에는 덤프 서버가 포함되어 있지 않습니다. 덤프 서버는 laravel/laravel 작곡가 파일의 개발 종속성이 됩니다.

See all articles