Laravel学习之旅(二)

控制器

  一、怎么编写控制器?

    1、控制器文件存放路径:appHttpControllers;

    2、命名规范如:TestController.php

    3、完整的控制器例子如下:

    

<?php

namespace AppHttpControllers;

class TestController extends Controller
{
    public function index()
    {
        return 'test';
    }
}

  

  二、控制器怎么与路由关联?

    1、方法:

      1.1

Route::any('test/index', 'TestController@index');

      1.2

Route::any('test/index', ['uses' => 'TestController@index']);

    2、起别名:

    

routes.php
Route::any('test/index', [
    'uses' => 'TestController@index',
    'as' => 'testindex']
);

TestController
public function index()
    {
        return route('testindex');
    }

  

  三、关联路由后,路由的特性怎么用?

    1、绑定参数:

    

    Route::any('test/{id}', 'TestController@index'); // 路由绑定id参数

    public function index($id)
    {
        return $id; // 方法接受参数,并返回
    }

    2、对绑定的参数进行限制:

Route::any('test/{id}', 'TestController@index')->where('id', '[0-9]+'); // 限制id参数类型必须是0-9的数字

  

原文地址:https://www.cnblogs.com/timothy-lai/p/6419397.html