首页 - 技术 - 初探laravel强大的功能性路由(二)

初探laravel强大的功能性路由(二)

2023-09-30 20:31
-->

目标当然是先输出helloworld

配置apache下的hosts文件和httpd-vhosts.conf,

主机:127.0.0.1 www.gsm-guard.net

httpd-vhosts.conf:


DocumentRoot "D:\www\htdocs\blog\laravel\public"
ServerName www.gsm-guard.net

以下代码均在routes.php中操作

//基本路由1
Route::get('/',function(){
返回 '​​helloworld';
});

输出如下:

//基本路由2
//不能直接进入post方法访问路由
Route::post('test1',function(){
返回“帖子”;
});

//基本路由3
Route::get('test',function(){
返回'testx';
});

//多个请求
路线::match(['get','post'],'xx/xx',function(){
return 'heihei1';
});
//或者
路线::any('xx/xx',function(){
return 'heihei2';
});

//路由传递参数
路线::get('user/{id}',function($id){
return '用户的id是'.$id;
});//两个参数
路线::get('user/{name}/{id}',function($name,$id){
return '用户的名字是'.$name.'用户的id是'.$id;
});

//路由可选参数
Route::get('user/{name?}',function($name=null){
return '用户的名字是'.$name;
});

//参数限制where(),使用正则判断
路线::get('用户/{name}',function($name){
return '用户的名字是'.$name;
})->where('名称','[a-zA-Z]+'); //多参数限制
路线::get('user/{name}/{id}',function($name,$id){
return '用户的名字是'.$name.'用户的id是'.$id;
})->where(['name'=>'[a-zA-Z]+','id'=>'\d+']);
//控制器路由,前面的参数随便填,只要你高兴就好
//比如admin/test或者test或者nikaixinjiuhao或者xx/xx/xxx/xxx/xx/xx,仍然可以访问
路线::get('xxx/xx','TestController@hello');
路线::get('xx/xx/xxx/xxx/xx/xx','TestController@hello');

//routes.php中
//控制器路由,前面的参数随便填,只要你高兴就行了
//比如admin/test或者test或者nikaixinjiuhao或者xx/xx/xxx/xxx /xx/xx ,仍然可以访问
Route::get('xxx/xx','Home\TestController@hello');
//直接在模块外写
Route::get('xx /xx/ xxx/xxx/xx/xx','Test2Controller@hello');

//控制器可以直接手动创建或者使用cmd命令行创建
//TestController.php
命名空间 App\Http\Controllers\Home;
使用 App\Http\Controllers\Controller;
类 TestController 扩展了 Controller{
公共函数 hello(){
echo '你好世界';
}
}
//Test2Controller.php
命名空间 App\Http\Controllers;
使用 App\Http\Controllers\Controller;
类 Test2Controller 扩展了 Controller{
公共函数 hello(){
echo '你好世界';
}
}

分配给模板:

TestController.php

//TestController.php
命名空间 App\Http\Controllers\Home;
使用 App\Http\Controllers\Controller;
类 TestController 扩展了 Controller{
公共函数 hello(){
返回“你好世界”;
} 公共函数 phptemplate(){
$data=['name'=>'zhangsan','userid'=>'39'];
返回视图('测试',$data);
} 公共函数 phpblade(){
$data=['name'=>'zhaowu','userid'=>'23'];
返回视图('test2',$data);
}
}

routes.php

路线::get('usertemplate','Home\TestController@phptemplate');
路线::get('userblade','Home\TestController@phpblade');

测试页面




这是php形式的模板


{{$name}}
{{$userid}}





test2.blade.php




这是phpblade的模板





{{$name}}
{{$userid}}

得到效果,两者的区别一目了然:

-->