PHP code example of limingxinleo / x-phalcon-middleware
1. Go to this page and download the library: Download limingxinleo/x-phalcon-middleware library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
limingxinleo / x-phalcon-middleware example snippets
use Xin\Phalcon\Middleware\Mvc\Dispatcher as MvcDispatcher;
use Xin\Phalcon\Middleware\Mvc\Dispatcher71 as MvcDispatcher71;
$di->setShared('middlewareManager', function () {
$middlewareManager = new Manager();
//注册中间件
$middlewareManager->add('test', \Tests\App\Middleware\Test1Middleware::class);
$middlewareManager->add('test2', \Tests\App\Middleware\Test2Middleware::class);
$middlewareManager->add('test3', \Tests\App\Middleware\Test3Middleware::class);
return $middlewareManager;
});
//替换默认的dispatcher
$di->setShared('dispatcher', function () {
if (version_compare(PHP_VERSION, '7.1', '>')) {
$dispatcher = new MvcDispatcher71();
} else {
$dispatcher = new MvcDispatcher();
}
$dispatcher->setDefaultNamespace('Tests\App\Controllers');
return $dispatcher;
});
~~~
## 使用
* 创建中间件
~~~php
namespace App\Middleware;
use Xin\Phalcon\Middleware\Middleware;
class Aaa extends Middleware
{
public function handle($request ,\Closure $next)
{
//在中间件中使用service
if($this->request->isAjax()){
return $this->response->redirect('/login');
}
//前置操作
echo __METHOD__.'<hr>';
$response = $next($request);
//后置操作
echo __METHOD__.'<hr>';
return $response;
}