Skip to content

Commit

Permalink
Event.php is added, Also used in Application.php
Browse files Browse the repository at this point in the history
  • Loading branch information
hussainaliweb committed Apr 8, 2022
1 parent 3918564 commit c9cd1b0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
24 changes: 18 additions & 6 deletions Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
namespace hussainalihussain\phpmvclaravelclonecore;

use hussainalihussain\phpmvclaravelclonecore\database\Database;
use app\models\User;

class Application
class Application extends Event
{
/**
* @var Router
Expand Down Expand Up @@ -65,6 +64,16 @@ public function __construct(string $root_path, array $config = [])
$this->session = new Session();
$this->userClassName = $config['userClassName'] ?? '';
}

public function registerErrorEvent(\Throwable $t)
{
$this->on(Event::EVENT_ERROR_OCCUR, function() use ($t) {
$this->response->setCode($t->getCode());
echo $this->view->renderView('_error', [
'exception'=> $t
]);
});
}

/**
* @return void
Expand All @@ -73,14 +82,17 @@ public function run()
{
try
{
$this->trigger(EVENT::EVENT_BEFORE_REQUEST);
echo $this->router->resolve();
}
catch (\Exception $e)
{
$this->response->setCode($e->getCode());
echo $this->view->renderView('_error', [
'exception'=> $e
]);
$this->registerErrorEvent($e);
$this->trigger(Event::EVENT_ERROR_OCCUR);
}
finally
{
$this->trigger(Event::EVENT_AFTER_REQUEST);
}
}

Expand Down
26 changes: 26 additions & 0 deletions Event.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace app\core;

abstract class Event
{
public const EVENT_BEFORE_REQUEST = 'beforeRequest';
public const EVENT_AFTER_REQUEST = 'afterRequest';
public const EVENT_ERROR_OCCUR = 'errorOccur';
protected $eventListeners = [];

public function on(string $eventName, $callback)
{
$this->eventListeners[$eventName][] = $callback;
}

public function trigger(string $eventName)
{
$callbacks = $this->eventListeners[$eventName] ?? [];

foreach ($callbacks as $callback)
{
call_user_func($callback);
}
}
}

0 comments on commit c9cd1b0

Please sign in to comment.