本文实例讲述了Laravel5.1 框架控制器基础用法。分享给大家供大家参考,具体如下:
为什么要使用控制器
像我们之前写一些逻辑呢都是在Route(路由)中,搞得Route文件特别庞大,其实我们应该把这些逻辑都抽到一个控制器里,路由分发后到控制器,控制器做相应的操作,比如关于后台的逻辑应该抽到AdminController中,Route文件只管分发。
1 如何创建一个控制器
1.1.1 创建RESTful控制器
至于什么是RESTful?自行百度- -,我先简单说下,它里面自动填充了一些增删改查的方法。OK 我们在Artisan控制台创建:
php artisan make:controller Admin\\HomeController
然后 我们在 app/Http/Controller/Admin/ 下找到它:
class HomeController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    //
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param \Illuminate\Http\Request $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    //
  }
  /**
   * Display the specified resource.
   *
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function show($id)
  {
    //
  }
  /**
   * Show the form for editing the specified resource.
   *
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function edit($id)
  {
    //
  }
  /**
   * Update the specified resource in storage.
   *
   * @param \Illuminate\Http\Request $request
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    //
  }
  /**
   * Remove the specified resource from storage.
   *
   * @param int $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    //
  }
}
每个方法就是它的字面意思,至于怎么使用,我们来注册一条路由就清楚了。
1.1.2 实现RESTful路由
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function (){
  Route::resource('/', 'HomeController');
});
resource是为RESTful风格的控制器注册多条路由的 我们可以在Artisan控制台看看:
php artisan route:list
如果没有什么错误的话,咱肯定会看见打印出来的表,表里面标明了每条路由的属性,如果你还是不太明白,那无所谓~咱以后的文章会频繁使用到这些内容哦。
1.2.1 普通控制器
在实际开发中啊 有时候咱不一定需要RESTful风格的服务器,我们只想要一个空的控制器来自己实现一些方法,可以这么生成:
