Monday, May 25, 2015

Contoh penggunaan Controller

1. Anda ingin filter sebelum  actions pada controller tertentu :


pilihan 1 , anda boleh guna :

app/filters.php

pilihan 2 , 

Controller::beforeFilter()

contoh :

class MyController extends \Controller
{
    public function __construct()
    {
        $this->beforeFilter('auth');
    }
}
 
 
boleh tambah atribute macam router :
 
class MyController extends \Controller
{
    public function __construct()
    {
        $this->beforeFilter('auth', ['except' => 'login']);
        $this->beforeFilter('csrf', ['on' => 'post']);
    }
}
 
atau guna closer :
 
class MyController extends \Controller
{
    public function __construct()
    {
        $this->beforeFilter(function()
        {
            if (date('G') < 6)
            {
                return "This website doesn't work before 6am";
            }
        });
    }
}
 


2. Anda ingin filter selepas actions pada controller tertentu.

Opsyen 1 :

app/filters.php

opsyen 2 :

guna Controller::afterFilter()

Contoh :


class MyController extends \Controller
{
    public function __construct()
    {
        $this->afterFilter('log');
    }
}
 
dengan closure :
 
class MyController extends \Controller
{
    public function __construct()
    {
        // dump last response
        $this->afterFilter(function($route, $request, $response)
        {
            $content = $response->getContent();
            File::put(app_storage().'/logs/last_response', $content);
        });
    }
}
 
 
3. Dapatakan Before dan After Filters Controller

class SomeController extends Controller {
    public function someMethod()
    {
        // Dump all the before filters
        var_dump($this->getBeforeFilters());
    }
}
 
guna getAfterFilters() atau getBeforeFilters() 


 

No comments:

Post a Comment