laravel基础知识学习总结(路由、中间件、控制器)

 路由:

  • 路由:是将信息从源地址传递到目的地得角色
  • Route::get('/test',function(){ });   //分号不能丢
  • 报错信息MethodNotAllowedHttpException in RouteController.php 说明当前得请求方式和路由规则不匹配
  • laravel框架中所有得模板文件都是存放在resources/views中
  • 模板文件得后缀名是 .blade.php
  • 错误信息TokenMismatchException in VerifyCsrfToken.php 说明当前得post请求中缺少验证信息.在每一个post表单中需要添加一个token
  • 当前路由规则中的参数名可以和匿名函数或者方法中的参数名,不保持一致.潜规则保持一致

routes.php

 1 <?php
 2 //基本路由
 3 Route::get('/',function(){
 4     return view('welcome');
 5 });
 6 //路由组
 7 Route::group([],function(){
 8     //带参数的路由
 9     Route::get('/user/{id}',function($ids){
10         echo "当前用户的id为".$ids;
11     });
12 
13     //阻止参数的类型
14     Route::get('/goods/{id}',function($id){
15         echo "商品的详情页..当前id为".$id;
16     })->where('id','\d+');
17 
18     //多个参数
19     Route::get('/{type}-{id}',function ($type,$id){ //该处的参数一定要传,不然下面无法使用这个参数
20         echo "我的类型是".$type."我的id是".$id;
21     });
22 
23     //路由别名
24     Route::get('Admin/User/index',[
25         'as'=>'bieming',    //as和uses是固定的,不可修改
26         'uses'=>function(){
27             echo route('bieming');  //route是一个函数,通过路由别名来快速创建完整的url
28         }
29     ]);
30 
31     //404页面
32     Route::get('/404',function(){
33     //    -------------------方式1-------------------
34     //    abort(404);
35     //    -------------------方式2-------------------
36         return view('errors.404');
37     });
38 });

 中间件

中间件:过滤请求

  • 创建:php artisan make:middleware TestMiddelware
  • 默认存放目录:app\http\middelware中
  • $request是laravel框架对请求报文做的封装

 使用:

  1. 创建中间件
    //创建中间件(文件位置:App\Http\Middleware)
     php artisan  make:middleware LoginMiddleware
  2. 注册
    //注册分为全局注册和路由注册(位置:App\Http\Kernel.php)
    //    设置全局注册
        protected $middleware = [
            \App\Http\Middleware\TestMiddelware::class,     //该句打印出来的是TestMiddelware的路径(App\Http\Middleware\TestMiddelware)
        ];
    
    //    设置路由注册
        protected $routeMiddleware = [
            'login'=>\App\Http\Middleware\LoginMiddleware::class,
        ];
  3. 使用(全局注册不需要该步,因为全局注册是针对所有的请求
    <?php
    //方式1
        Route::get('/setting',[
            'middleware'=>'login',
            'uses'=>function(){
            echo "这是设置页面。。。。";
            }
        ]);
    //方式2
        Route::get('/admin',function(){
            echo "这是网站的后台";
        })->middleware('login');
    }); 

 示例代码:

App\Http\kernel.php

 1 <?php
 2 
 3 namespace App\Http;
 4 
 5 use Illuminate\Foundation\Http\Kernel as HttpKernel;
 6 
 7 class Kernel extends HttpKernel
 8 {
 9     /**
10      * The application's global HTTP middleware stack.
11      *
12      * @var array
13      */
14 //    设置全局注册
15     protected $middleware = [
16         \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
17         \App\Http\Middleware\EncryptCookies::class,
18         \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
19         \Illuminate\Session\Middleware\StartSession::class,
20         \Illuminate\View\Middleware\ShareErrorsFromSession::class,
21         \App\Http\Middleware\VerifyCsrfToken::class,
22         \App\Http\Middleware\TestMiddelware::class,     //该句打印出来的是TestMiddelware的路径(App\Http\Middleware\TestMiddelware)
23     ];
24 
25     /**
26      * The application's route middleware.
27      *
28      * @var array
29      */
30 //    设置路由注册
31     protected $routeMiddleware = [
32         'auth' => \App\Http\Middleware\Authenticate::class,
33         'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
34         'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
35         'login'=>\App\Http\Middleware\LoginMiddleware::class,
36     ];
37 }
View Code

app\Http\Middleware\TestMiddelware.php

 1 <?php
 2 
 3 namespace App\Http\Middleware;
 4 
 5 use Closure;
 6 
 7 class TestMiddelware
 8 {
 9     /**
10      * Handle an incoming request.
11      *
12      * @param  \Illuminate\Http\Request  $request
13      * @param  \Closure  $next
14      * @return mixed
15      */
16     public function handle($request, Closure $next)
17     {
18 //       记录该请求的路径
19 //        [2018-08-08 08:08:08]127.0.0.1-------/Admin/User/index
20         $path='['.date('Y-m-d H:i:s') .']'.$request->ip().'-------'.$request->path();
21 //        将字符串路径存放到日志中
22         file_put_contents('request.log',$path."\r\n",FILE_APPEND);
23 //        进入下一层的代码执行
24         return $next($request);
25     }
26 }
View Code

app\Http\Middleware\LoginMiddleware.php

 1 <?php
 2 
 3 namespace App\Http\Middleware;
 4 
 5 use Closure;
 6 
 7 class LoginMiddleware
 8 {
 9     /**
10      * Handle an incoming request.
11      *
12      * @param  \Illuminate\Http\Request  $request
13      * @param  \Closure  $next
14      * @return mixed
15      */
16     public function handle($request, Closure $next)
17     {
18 //        检测请求是否具有session信息
19         if (!session('uid')) {
20             //跳转
21             return redirect('/login');
22         }
23         return $next($request);
24     }
25 }
View Code

route.php

 1 <?php
 2     Route::get('/setting',[
 3         'middleware'=>'login',
 4         'uses'=>function(){
 5         echo "这是设置页面。。。。";
 6         }
 7     ]);
 8     Route::get('/session',function(){
 9         session(['uid'=>10]);
10     });
11     Route::get('/login',function(){
12         echo "这里是用户的登陆页面";
13     });
14     //网站后台
15     Route::get('/admin',function(){
16         echo "这是网站的后台";
17     })->middleware('login');
18 });
View Code

 控制器

  •  概念:控制model和view
  • 创建控制器
    //方式1
    php artisan   make:controller UserController
    //方式2.创建一个空控制器
    php artisan   make:controller TestController --plain(不创建类方法) 

资源控制器的访问规则:

Verb    Path                        Action  Route Name
GET     /users                      index   users.index
GET     /users/create               create  users.create
POST    /users                      store   users.store
GET     /users/{user}               show    users.show
GET     /users/{user}/edit          edit    users.edit
PUT     /users/{user}               update  users.update
DELETE  /users/{user}               destroy users.destroy

隐式控制器和资源控制器示例代码:

route.php

<?php
    //隐式控制器
    Route::controller('cmftest','TestController');
    //资源控制器
    Route::resource('user','UserController');
});

TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class TestController extends Controller
{
//    函数名称必须为”method+访问名称“
//    访问名称的第一次字母大写
//    访问地址:localhost:10/cmftest/test
    public function getTest()
    {
        return "这是test函数";
    }
}

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    //访问路径:http://localhost:10/user
    public function index()
    {
        echo "index";
    }
    //访问路径:http://localhost:10/user/create
    public function create()
    {
        echo "create";
    }
}

脑图总结: 

脑图地址:http://naotu.baidu.com/file/f7317bc2f0f514db9e996b7705255910?token=b53e299981abe1da

 

posted @ 2018-08-24 17:32  花花妹子。  阅读(674)  评论(0编辑  收藏  举报