Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

藏色散人
풀어 주다: 2021-07-26 09:11:17
앞으로
2730명이 탐색했습니다.

일상적으로 일부 사용자 작업 이벤트를 처리할 때 나중에 참조하거나 빅데이터 통계를 위해 기록해야 하는 경우가 있습니다.


Laravel은 모델 이벤트를 처리하는 데 매우 편리합니다: https://laravel-china.org/docs/laravel/5.5/eloquent#events


Laravel의 모델 이벤트에는 두 가지 방법이 있습니다.

  • settingsdispatchesEvents속성 매핑 이벤트 클래스
  • dispatchesEvents属性映射事件类
  • 使用观察器来注册事件,这里介绍第二种
  • 新建模型

php artisan make:model Log

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Log extends Model
{
    protected $fillable = [&#39;user_name&#39;, &#39;user_id&#39;, &#39;url&#39;, &#39;event&#39;, &#39;method&#39;, &#39;table&#39;, &#39;description&#39;];
}
로그인 후 복사
  • 创建迁移表:

php artisan make:migration create_logs_table

  • 表的结构大概是这样,可按需设计
<?php use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create(&#39;logs&#39;, function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('user_id')->comment('操作人的ID');
            $table->string('user_name')->comment('操作人的名字,方便直接查阅');
            $table->string('url')->comment('当前操作的URL');
            $table->string('method')->comment('当前操作的请求方法');
            $table->string('event')->comment('当前操作的事件,create,update,delete');
            $table->string('table')->comment('操作的表');
            $table->string('description')->default('');
            $table->timestamps();
        });

        DB::statement("ALTER TABLE `logs` comment '操作日志表'");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('logs');
    }
}
로그인 후 복사
  • 运行迁移生成表

php artisan migrate

  • 新建一个服务提供者统一注册所有的模型事件观察器(后面的名字可以自己起得形象一点)

php artisan make:provider ObserverLogServiceProvider

  • /config/app.php中的providers数组注册(大概如图中)

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

  • app目录下新建文件夹Observers存放模型观察器,并新建基类LogBaseServer并在构造函数构建基本属性(CLI是因为在命令行执行时不存在用户执行)

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

  • 新建一个观察器继承基类LogBaseServerUser模型,方法的名字要对应文档中的事件)

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

  • 到新建的服务提供者ObserverLogServiceProvider中运行

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

  • 为需要的模型注册事件(我这挺多的,之后大概长这样)

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

  • 然后我们触发一些事件(增删改,表的数据就有了)

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명


  • 多对多的关联插入不会出触发模型(比如attach方法)
  • 这时候就需要自己新建事件类来模拟(这里拿分配权限给角色粗略说一下)

1.在EventServiceProvider中的listen属性绑定好事件

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

2.事件PermissionRoleEvent中的注入两个参数,一个是角色,另一个是attach或者detach관찰자를 사용하여 이벤트를 등록합니다. 두 번째 방법은 다음과 같습니다.

새 모델

php artisan make: model Log code><span class="img-wrap">rrreee<img class="lazy" referrerpolicy="no-referrer" src="/img/remote/1460000013815118?w=1345&h=665" alt="" title=""><img src="https://img.php.cn/upload/image/492/109/627/1627023592973459.png" title="1627023592973459.png" alt="Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명">마이그레이션 테이블 생성:</span><code>php artisan make:migration create_logs_table

🎜🎜테이블의 구조는 대략 다음과 같으며 다음과 같이 설계할 수 있습니다. 필요 rrreee🎜🎜마이그레이션 생성 테이블 실행 🎜php artisan migration🎜🎜🎜모든 모델 이벤트를 균일하게 등록하기 위해 새로운 서비스 공급자 생성 관찰자(후자의 이름은 여러분이 더 생생할 수 있습니다)🎜php artisan make:provider ObserverLogServiceProvider🎜🎜🎜to /config/app.php providers 배열 등록(아마도 그림에 표시됨)🎜🎜Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜🎜🎜🎜 app 디렉터리에 모델 관찰자를 저장할 새 폴더 Observers를 만들고, 새로운 기본 클래스 LogBaseServer 및 생성자에 기본 속성 구축(CLI는 명령줄에서 실행할 때 사용자 실행이 없기 때문입니다)🎜🎜Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜🎜🎜🎜기본 클래스를 상속할 새 관찰자를 만듭니다. 코드>LogBaseServer ( 🎜User🎜 모델, 메소드 이름 문서의 이벤트에 대응)🎜🎜 Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜🎜🎜🎜새로 생성된 서비스 공급자 ObserverLogServiceProvider로 이동하여 실행🎜🎜Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜🎜🎜🎜필요한 모델에 대한 이벤트를 등록합니다. 그 중 아마도 그럴 것이다. 앞으로는 이렇게 될 것입니다)🎜🎜Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜🎜🎜🎜 그런 다음 몇 가지 이벤트(추가, 삭제, 수정, 테이블 데이터가 있습니다)를 트리거합니다.🎜🎜Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜 🎜🎜🎜🎜다대다 연관 삽입은 트리거 모델을 생성하지 않습니다(예: 첨부 방법)🎜이번에는 이를 시뮬레이션하기 위해 새 이벤트 클래스를 생성해야 합니다. (여기서는 대략적으로 역할에 권한을 할당합니다.) 이에 대해 이야기합니다.)🎜1. EventServiceProvider🎜🎜🎜Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명🎜🎜🎜2. PermissionRoleEvent 이벤트에 두 개의 매개변수를 삽입합니다. 하나는 role이고 다른 하나는 attach 또는 분리🎜🎜🎜🎜🎜🎜🎜

3. 이벤트 리스너 PermissionRoleEventLog도 기본 클래스 LogBaseServer를 상속합니다. 여기서는 전달된 배열 ID에 따라 순회한 다음 로그 PermissionRoleEventLog也继承基类LogBaseServer,这里就是根据传入的数组id遍历,然后创建日志

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

4.之后应用事件

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명


  • 更优雅的处理登录注销事件

1.在EventServiceProvider中的subscribe

Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명4. 이벤트는 추후 적용

82821acbffec3f624d392f5b2cb3b44.png

  • honthout and er hone and geation and geation li>1 EventServiceProvidersubscribe 속성을 ​​처리된 클래스

    Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

    2에 바인딩합니다.

    Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명

  • 3. 그 후의 효과는 다음과 같습니다:

    🎜🎜🎜관련 권장 사항: 🎜최신 5개 Laravel 비디오 튜토리얼🎜🎜🎜 🎜🎜

    위 내용은 Laravel 모델 이벤트의 두 가지 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    관련 라벨:
    원천:segmentfault.com
    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!