Table des matières
Setting the stage#
Introducing Event Annotations#
Conclusion#
Maison 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);
});
Copier après la connexion

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');
Copier après la connexion

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
    );
  }
}
Copier après la connexion

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');
Copier après la connexion

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.

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment obtenir le code de retour lorsque l'envoi par e-mail échoue à Laravel? Comment obtenir le code de retour lorsque l'envoi par e-mail échoue à Laravel? Apr 01, 2025 pm 02:45 PM

Méthode pour obtenir le code de retour lorsque l'envoi par e-mail de Laravel échoue. Lorsque vous utilisez Laravel pour développer des applications, vous rencontrez souvent des situations où vous devez envoyer des codes de vérification. Et en réalité ...

La tâche de calendrier Laravel n'est pas exécutée: que dois-je faire si la tâche n'est pas en cours d'exécution après le calendrier: Exécuter la commande? La tâche de calendrier Laravel n'est pas exécutée: que dois-je faire si la tâche n'est pas en cours d'exécution après le calendrier: Exécuter la commande? Mar 31, 2025 pm 11:24 PM

Laravel Schedule Tâche d'exécution de dépannage non réactif Lorsque vous utilisez la planification des tâches de calendrier de Laravel, de nombreux développeurs rencontreront ce problème: Schedule: Exécuter ...

Dans Laravel, comment gérer la situation où les codes de vérification ne sont pas envoyés par e-mail? Dans Laravel, comment gérer la situation où les codes de vérification ne sont pas envoyés par e-mail? Mar 31, 2025 pm 11:48 PM

La méthode de traitement de l'échec de l'e-mail de Laravel à envoyer le code de vérification est d'utiliser Laravel ...

Comment implémenter la fonction de table personnalisée de clic pour ajouter des données dans l'administrateur DCAT? Comment implémenter la fonction de table personnalisée de clic pour ajouter des données dans l'administrateur DCAT? Apr 01, 2025 am 07:09 AM

Comment implémenter la fonction du tableau de Cliquez sur personnalisé pour ajouter des données dans DCATADMIN (Laravel-Admin) lors de l'utilisation de DCAT ...

Partage de connexion Laravel Redis: pourquoi la méthode de sélection affecte-t-elle d'autres connexions? Partage de connexion Laravel Redis: pourquoi la méthode de sélection affecte-t-elle d'autres connexions? Apr 01, 2025 am 07:45 AM

L'impact du partage des connexions redis dans Laravel Framework et sélectionnez Méthodes Lors de l'utilisation de Laravel Framework et Redis, les développeurs peuvent rencontrer un problème: grâce à la configuration ...

Laravel Multi-Lenant Extension Stancl / Tenancy: Comment personnaliser l'adresse hôte d'une connexion de base de données de locataire? Laravel Multi-Lenant Extension Stancl / Tenancy: Comment personnaliser l'adresse hôte d'une connexion de base de données de locataire? Apr 01, 2025 am 09:09 AM

Connexion de la base de données des locataires personnalisés dans le package d'extension multi-locataire Laravel Stancl / location Lors de la construction d'applications multi-locataires à l'aide du package d'extension multi-locataire Laravel Stancl / location, ...

Laravel Eloquent Orm dans Bangla Partial Model Search) Laravel Eloquent Orm dans Bangla Partial Model Search) Apr 08, 2025 pm 02:06 PM

Laravelelognent Model Retrieval: Faconttement l'obtention de données de base de données Eloquentorm fournit un moyen concis et facile à comprendre pour faire fonctionner la base de données. Cet article présentera en détail diverses techniques de recherche de modèles éloquentes pour vous aider à obtenir efficacement les données de la base de données. 1. Obtenez tous les enregistrements. Utilisez la méthode All () pour obtenir tous les enregistrements dans la table de base de données: usApp \ Modèles \ Post; $ poters = post :: all (); Cela rendra une collection. Vous pouvez accéder aux données à l'aide de Foreach Loop ou d'autres méthodes de collecte: ForEach ($ PostsAs $ POST) {echo $ post->

Quel est le meilleur, Django ou Laravel? Quel est le meilleur, Django ou Laravel? Mar 28, 2025 am 10:41 AM

Django et Laravel sont tous deux des frameworks à pile. Django convient aux développeurs Python et à la logique métier complexe, tandis que Laravel convient aux développeurs PHP et à la syntaxe élégante. 1.Django est basé sur Python et suit la philosophie "Battery-Complete", adaptée au développement rapide et à une grande concurrence. 2.Laravel est basé sur PHP, mettant l'accent sur l'expérience du développeur et convient aux projets de petite et moyenne taille.

See all articles