Laravel学习总结二:基础内容(Controller)

Laravel学习总结二:基础内容(Controller)

2015/1/4 更新,修改即更新,也欢迎大家批评指正。一起学习,广交编码同仁。

控制器:

Laravel为典型的MVC架构,其中的C角色就由控制器扮演,用来处理项目中的逻辑、处理判断的功能。

为了保持代码的低耦合和高复用,我们在写路由的控制操作的时候,一律不使用闭包,全部通过控制器来实现。


定义控制器

控制器类必须继承BaseController类,如下代码为Laravel自带的一个HomeController

<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function showWelcome()
	{
		return View::make('hello');
	}

}
该控制器用来返回一个名为‘hello’ 的View视图,这里简单说下请求的处理思路:请求到路由时,由路由进行判断进行何种过滤操作,再进行何种控制器中的逻辑处理,处理完了之后,再返回一个response,该response一般就为一个View视图。

在控制器中定义过滤器

但是个人觉得这样的功能没啥用,在filter完全可以在Route进行关联。所以这里我不推荐

只要知道能这么做就可以了

三种方式:

1在控制器类中的构造方法中

__construct()中指定过滤器

 public function __construct()
    {
        $this->beforeFilter('auth', array('except' => 'getLogin'));

        $this->beforeFilter('csrf', array('on' => 'post'));

        $this->afterFilter('log', array('only' =>
                            array('fooAction', 'barAction')));
    }

$this->beforefilter('auth',['except'=>'getlogin']);

2.在构造方法中,定义闭包函数来定义过滤方式

 public function __construct()
    {
        $this->beforeFilter(function()
        {
            //
        });
    }

3.在构造方式中,指定该控制器类中的其他方法来进行过滤操作

 public function __construct()
    {
        $this->beforeFilter('@filterRequests');
    }

    /**
     * Filter the incoming requests.
     */
    public function filterRequests($route, $request)
    {
        //
    }


隐式控制器

我本人并没有使用过该方式,只是将学习的东西记录下来
Route::controller('users', 'UserController');
该路由直接与UserController控制器类进行绑定,

首先

该Route::controller中有两个参数:
1.为URL中的基底
2.为控制器的类

其次:

Next, just add methods to your controller, prefixed with the HTTP verb they respond to:
(官方文档copy     https://laravel.com/docs/4.2/controllers#restful-resource-controllers)
需要在该控制器类中创建方法,方法名为(前缀+资源),前缀为请求的action方式 such as   GET  POST 
class UserController extends BaseController {

    public function getIndex()
    {
        //该方法是直接返回response
    }

    public function postProfile()
    {
        //使用post 该users/profile的url时,调用该方法来进行处理
    }

    public function anyLogin()
    {
        // 任何方式get/post 获取该users/login 的URL时,该方法进行处理
    }
    public function getAdminProfile() 
    {
        //该方法对应的URL为    users/admin-profile
    }
}


 
  




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值