您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
webman-路由-处理404
发布时间:2022-01-19 22:29:50编辑:雪饮阅读()
控制器\app\controller\Foo.php编码如:
<?php
namespace app\controller;
use support\Request;
class Foo
{
/**
* 该方法会在请求前调用
*/
public function beforeAction(Request $request)
{
echo 'beforeAction';
// 若果想终止执行Action就直接返回Response对象,不想终止则无需return
// return response('终止执行Action');
}
/**
* 该方法会在请求后调用
*/
public function afterAction(Request $request, $response)
{
echo 'afterAction';
// 如果想串改请求结果,可以直接返回一个新的Response对象
// return response('afterAction');
}
public function index(Request $request,$id)
{
return response(route('blog.view', ['id' => 100]));
}
public function index2(Request $request)
{
return response('foo index2');
}
public function edit2(Request $request)
{
return response('foo edit2');
}
public function notFound(Request $request)
{
return response('i am so sorry:页面未找到!');
}
}
config/route.php编码如:
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Webman\Route;
Route::any('/blog/{id}', [app\controller\Foo::class, 'index'])->name('blog.view');
Route::any('/notFound', [app\controller\Foo::class, 'notFound']);
Route::fallback(function(){
return redirect('/notFound');
});
此时请求一个不存在的路由时候:
[root@localhost ~]# elinks http://127.0.0.1:8787/blo --dump
页面未找到!
就自动重定向到上面的notFound路由了。
还可以配置未json方式返回404,像是上面的config/route.php修改后:
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Webman\Route;
Route::any('/blog/{id}', [app\controller\Foo::class, 'index'])->name('blog.view');
Route::any('/notFound', [app\controller\Foo::class, 'notFound']);
Route::fallback(function(){
return json(['code' => 404, 'msg' => '404 not found']);
});
再次请求以json方式返回:
[root@localhost ~]# elinks http://127.0.0.1:8787/blo --dump
{"code":404,"msg":"404 not found"}
关键字词:webman,路由,处理,404
上一篇:webman-路由-url生成