php 实现before事件
在 PHP 中实现类似 "before" 事件(即在某个操作执行前触发的逻辑),可以通过以下方法实现:
使用面向对象设计模式
通过装饰器模式或钩子(Hook)机制,在目标方法执行前插入逻辑:
class EventDispatcher {
private $beforeCallbacks = [];
public function before(callable $callback) {
$this->beforeCallbacks[] = $callback;
}
public function execute() {
foreach ($this->beforeCallbacks as $callback) {
call_user_func($callback);
}
// 主逻辑执行
echo "Main logic executed\n";
}
}
$dispatcher = new EventDispatcher();
$dispatcher->before(function() {
echo "Before event triggered\n";
});
$dispatcher->execute();
使用魔术方法 __call
通过魔术方法拦截方法调用,在方法执行前触发事件:
class BeforeEventExample {
public function __call($name, $arguments) {
if (method_exists($this, 'before'.$name)) {
call_user_func([$this, 'before'.$name]);
}
return call_user_func_array([$this, $name], $arguments);
}
protected function beforeAction() {
echo "Before action triggered\n";
}
protected function action() {
echo "Main action executed\n";
}
}
$example = new BeforeEventExample();
$example->action();
使用 trait 实现复用
通过 trait 封装 before 事件逻辑,实现多类复用:
trait BeforeEventTrait {
protected $beforeHandlers = [];
public function before($event, callable $handler) {
$this->beforeHandlers[$event][] = $handler;
}
protected function triggerBefore($event) {
if (isset($this->beforeHandlers[$event])) {
foreach ($this->beforeHandlers[$event] as $handler) {
$handler();
}
}
}
}
class Example {
use BeforeEventTrait;
public function doSomething() {
$this->triggerBefore('doSomething');
echo "Main operation\n";
}
}
$example = new Example();
$example->before('doSomething', function() {
echo "Before hook\n";
});
$example->doSomething();
使用 AOP(面向切面编程)
通过第三方库如 Go! AOP 实现更专业的切面编程:
// 需要安装 goaop/framework
use Go\Core\AspectContainer;
use Go\Core\AspectKernel;
class BeforeAspect implements \Go\Aop\Aspect {
public function beforeMethod(\Go\Aop\Intercept\MethodInvocation $invocation) {
echo "Before " . $invocation->getMethod()->getName() . " execution\n";
}
}
class ApplicationAspectKernel extends AspectKernel {
protected function configureAop(AspectContainer $container) {
$container->registerAspect(new BeforeAspect());
}
}
class TargetClass {
public function targetMethod() {
echo "Target method executed\n";
}
}
ApplicationAspectKernel::getInstance()->init([
'debug' => true,
'appDir' => __DIR__,
'cacheDir' => __DIR__.'/cache'
]);
$target = new TargetClass();
$target->targetMethod();
以上方法根据复杂度需求可选择不同实现方案,从简单回调到专业 AOP 框架均可满足 before 事件的实现需求。







