thinkphp中如何使用event事件
thinkphp中如何使用event事件?
ThinkPHP6.0 event(事件)的使用方法
新版的事件系统可以看成是5.1版本行为系统的升级版,事件系统相比行为系统强大的地方在于事件本身可以是一个类,并且可以更好的支持事件订阅者。
事件相比较中间件的优势是事件比中间件更加精准定位(或者说粒度更细),并且更适合一些业务场景的扩展。例如,我们通常会遇到用户注册或者登录后需要做一系列操作,通过事件系统可以做到不侵入原有代码完成登录的操作扩展,降低系统的耦合性的同时,也降低了BUG的可能性。
TP6.0 文档中关于事件写了很多,有定义事件,有事件监听,还有事件订阅,实在让人头大
在网上翻了多篇博文,最终发现,它们是事件的不同实现方式 /(ㄒoㄒ)/~~
1.事件绑定
事件绑定不如其他两种方法使用方便,这里就暂不介绍了
2.事件监听
2-1.手动注册事件监听
我们可以手动注册一个事件监听
<?php namespace app\controller; use think\facade\Event; class Index { public function __construct(){ Event::listen('first', function($param){ echo $param . '+'; }); } public function index() { event('first', 'first success'); return 111; } }
2-2.使用监听类实现监听
首先我们通过命令行快速生成一个监听类
php think make:listener TestListener
修改 TestListener.php 文件代码
<?php declare (strict_types = 1); namespace app\listener; class TestListener { /** * 事件监听处理 * * @return mixed */ public function handle($event) { // echo "testListner监听成功"; } }
然后我们在index控制器中注册监听事件
<?php namespace app\controller; use think\facade\Event; class Index { public function index() { Event::listen('test', 'app\listener\TestListener'); event('test'); return 111; } }
此时我们访问index控制器下的index方法就可以看到监听成功的返回了
当然我们有更简便的方法注册监听类!
修改event.php文件,添加事件监听
<?php // 事件定义文件 return [ 'bind' => [ ], 'listen' => [ 'AppInit' => [], 'HttpRun' => [], 'HttpEnd' => [], 'LogLevel' => [], 'LogWrite' => [], 'test' => ['app\listener\TestListener'] ], 'subscribe' => [ ], ];
3.事件订阅
可以通过事件订阅机制,在一个监听器中监听多个事件
首先我们通过命令行生成一个订阅类 TestSub.php
<?php declare (strict_types = 1); namespace app\subscribe; class TestSub { public function onTestSub1(){ echo("testSub1"); } public function onTestSub2(){ echo("testSub2"); } }
然后调用这两个事件
<?php namespace app\controller; use think\facade\Event; use think\facade\Db; class Index { public function index() { event('TestSub1'); event('TestSub2'); return 111; } }
此时访问该接口就可以看到这两个事件的结果了
4.一些小心得
事件可以被主方法捕获异常!!!
主方法开启事务后,事件中若出现数据库错误,主方法可以捕获该异常并进行回滚等操作
首先,我们在 TestSub.php,对两个事件都进行数据库操作,其中一个数据库操作会报错
<?php declare (strict_types = 1); namespace app\subscribe; class TestSub { public function onTestSub1(){ echo("testSub1"); $data = ['id' => '1', 'username' => 'haha1']; \think\facade\Db::name('test')->save($data); echo("testSub11"); } public function onTestSub2(){ echo("testSub2"); $data = ['id' => '1', 'username' => 'haha1']; //test1表并不存在 \think\facade\Db::name('test1')->save($data); echo("testSub22"); } }
然后调用这两个事件,并开启事务
<?php namespace app\controller; use think\facade\Event; use think\facade\Db; class Index { public function index() { Db::startTrans(); try { event('TestSub1'); event('TestSub2'); // 提交事务 Db::commit(); return 111; } catch (\Exception $e) { // 回滚事务 Db::rollback(); echo($e); return 222; } } }
更多相关知识,请访问PHP中文网!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
