While it's kinda pointless, it's possible to use callbacks as URL handlers totally avoiding MVC in the same style as many micro-frameworks do.
require 'vendor/autoload.php';
require 'vendor/yiisoft/yii2/Yii.php';
$app = new CallbackWebApplication([
'id' => 'MyApplication',
'basePath' => __DIR__,
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
]);
$app->onGet('hello/<name>', function($name) {
return 'Hello, ' . $name . '!';
});
$app->run();
<?php
class CallbackWebApplication extends \yii\web\Application
{
private $callbacks = [];
/**
* @inheritdoc
*/
public function handleRequest($request)
{
list ($route, $params) = $request->resolve();
if (preg_match('~callbacks/(\d+)~', $route, $matches) && isset($this->callbacks[$matches[1]])) {
$result = call_user_func_array($this->callbacks[$matches[1]], $params);
} else {
throw new \yii\web\NotFoundHttpException();
}
$response = $this->getResponse();
$response->data = $result;
return $response;
}
public function onGet($pattern, callable $callback)
{
// it's possible to implement our own UrlRule class to handle it
// but I was too lazy
$callbackIndex = count($this->callbacks);
$this->callbacks[$callbackIndex] = $callback;
Yii::$app->getUrlManager()->addRules([
$pattern => 'callbacks/' . $callbackIndex
]);
}
}