[FP] Tạo dưng control function cho HTTP method trong Fuelphp

Post Reply
tthlan
Quản trị viên
Posts: 75
Joined: Tue Aug 23, 2016 8:13 am

[FP] Tạo dưng control function cho HTTP method trong Fuelphp

Post by tthlan »

Theo hướng dẫn tại site chính của FuelPHP, ta có thể tham khảo nhiều các xử lý với class Controller.

Ngoài mặc định route tới controller sẽ chạy là index() method, tuy nhiên khi ta muốn khi route tới controller thông qua phương thức GET hoặc phương thức POST, thì ta phải định method mặc định post() get() để xử lý cho việc đó

Code: Select all

class Controller_Example extends Controller
{
    public function get_index()
    {
        // This will be called when the HTTP method is GET.
    }

    public function post_index()
    {
        // This will be called when the HTTP method is POST.
    }
}
Giả sử controller là abc khi gõ trên url '/abc?p1=123' thì get_index() sẽ tiến hành xử lý. Nếu submit form tới /abc thì post_index() sẽ được gọi.



Ngoài ra còn một cách khác mình hay dùng qua là xử lý ngay trong action method của controller thông qua Input::method() : The method returns the HTTP method used to call the controller. If the header X-HTTP-Method-Override has been sent, the specified method will be returned instead.

Code: Select all

class Controller_Abc extends Controller
{
    public function abc_action()
    {
        if ( Input::method == 'GET')
        {
        	// Continue process for the HTTP method is GET, ex : $_GET['parameter_1'] : get value of parameter 1 of GET
        }
        else if ( Input::method == 'POST')
        {
        	// Continue process for the HTTP method is POST
        }
    }

    public function post_index()
    {
        // This will be called when the HTTP method is POST.
    }
}

Dựa trên đó, ta có thể xây dựng một method controll với nhiều tham số và trả về giá trị lên view như sau

Code: Select all

public function action_name_to_upper($name_1, $name_2)
{
    $data['v_1'] = strtoupper($name_1);
    $data['v_2'] = strtoupper($name_2);
    return View::forge('test/name_to_upper', $data);
}
Khi ta nhập url '/controler_name/name_to_upper/value_1/value_2', hệ thống sẽ trả và hiển thị view tại test/name_to_upper với 2 giá trị "value_1" and "value_2" sẽ được truyền qua biến mảng $data với thành phần mà giá trị nhận từ $name_1 and $name_2.

Lúc đó code php trên view ta có thể truy xuất bằng $v_1, $v_2 để hiển thị giá trị

Have fun with FuelPHP
Post Reply