12/08/2018, 09:32

Tạo server với các API theo chuẩn REST FUL trong CakePhp

Trong bài viết này, sẽ hướng dẫn các bước cụ thể tạo một RESTFUL service và client hoàn chỉnh trong cakephp. Lý thuyết về REST bạn có thể tham khảo ở link sau https://viblo.asia/khanhhd/posts/l5y8Rro9Mob3 Các bước cần thực hiện Bước 1: Tạo một database test Bước 2: Tạo phones ...

Trong bài viết này, sẽ hướng dẫn các bước cụ thể tạo một RESTFUL service và client hoàn chỉnh trong cakephp.

Lý thuyết về REST bạn có thể tham khảo ở link sau https://viblo.asia/khanhhd/posts/l5y8Rro9Mob3

Các bước cần thực hiện

Bước 1: Tạo một database test

  • 1.png

Bước 2: Tạo phones model, controller và view

  • Bước này nhắm mục đích giúp bạn hiểu rõ về CakePHP. Bạn sẽ tạo một phones model, controller và view theo tutorial http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html .

  • 2.png

  • Nếu bạn hiểu rõ về cakephp thì bạn có thể bỏ qua bước này.

Bước 3: Setup restfullness

  • Thêm hai dòng sau vào file app/config/routes.php
  • 
    

// app/config/routes.php Router::mapResources(‘phones’); Router:parseExtensions();

- Chú ý: Thêm hai dòng trên dòng

- ```PHP
require CAKE . 'Config' . DS . 'routes.php';
```

**Bước 4: Understanding cakephp rest routes**

- ![3.PNG](/uploads/7da27e2c-48f4-49e1-9f4b-59b429a36260.png)

**Bước 5: Create a restful controller**

- Lý do tại sao RestPhonesController tồn tại được là nó cho phép cung cấp một dịch vụ REST sạch có thể tách biệt với các ứng dụng thông thường. Nó cũng cho phép thêm các quy tắc tiền tố để nếu muốn bạn có thể tách biệt với lời gọi các trình duyệt thông thường với lời gọi từ REST API.
- RestPhoneController về cơ bản sử dụng giống với PhonesController nhưng chúng ta có thể thay đổi cho giới hạn hoặc thêm những thứ chúng ta muốn cho dịch vụ RESTful.
- Ví dụ, thử tưởng tượng trên các ứng dụng web, ban có thể chỉnh sửa các cuộc gọi nhưng trên dịch vụ RESTful, ban chỉ có thể muốn người dùng có thể sửa chữa giới hạn số lượng của các cuộc gọi... Có RestPhoneController, bạn cũng có thể tuân theo tất cảc các CakePHP's Rest routes. Bây giờ, tôi có các hành động mà nó là REST-specific và cũng tuân theo các định tuyến phù hợp.
- Đây là full code của RestPhoneController

- ```PHP
class RestPhonesController extends AppController {
	public $uses = array('Phone');
    public $helpers = array('Html', 'Form');
	public $components = array('RequestHandler');

	public function index() {
		$phones = $this->Phone->find('all');
        $this->set(array(
            'phones' => $phones,
            '_serialize' => array('phones')
        ));
    }

	public function add() {
		$this->Phone->create();
		if ($this->Phone->save($this->request->data))         {
			 $message = 'Created';
		} else {
			$message = 'Error';
		}
		$this->set(array(
			'message' => $message,
			'_serialize' => array('message')
		));
    }

	public function view($id) {
        $phone = $this->Phone->findById($id);
        $this->set(array(
            'phone' => $phone,
            '_serialize' => array('phone')
        ));
    }

	public function edit($id) {
        $this->Phone->id = $id;
        if ($this->Phone->save($this->request->data))         {
            $message = 'Saved';
        } else {
            $message = 'Error';
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }

	public function delete($id) {
        if ($this->Phone->delete($id)) {
            $message = 'Deleted';
        } else {
            $message = 'Error';
        }
        $this->set(array(
            'message' => $message,
            '_serialize' => array('message')
        ));
    }
}

```

- Chú ý: việc khai báo RequestHandlder là cần thiết

- ```PHP
public $components = array('RequestHandler');
```

**Bước 6: Setup a Test Client
**

- Tạo một ClientController sử dụng HttpSocket để thực hiện yêu cầu HTTP với các dịch vụ của REST.

- ```PHP
App::uses('HttpSocket', 'Network/Http');
class ClientController extends AppController {
	public $components = array('Security', 'RequestHandler');

	public function index(){

	}

	public function request_index(){
		// remotely post the information to the server
		$link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_phones.json';
		// die(var_dump($link));

		$data = null;
		$httpSocket = new HttpSocket();
		$response = $httpSocket->get($link, $data );
		$this->set('response_code', $response->code);
		$this->set('response_body', $response->body);

		$this -> render('/Client/request_response');
	}

	public function request_view($id){

		// remotely post the information to the server
		$link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_phones/'.$id.'.json';

		$data = null;
		$httpSocket = new HttpSocket();
		$response = $httpSocket->get($link, $data );
		$this->set('response_code', $response->code);
		$this->set('response_body', $response->body);

		$this -> render('/Client/request_response');
	}

	public function request_edit($id){

		// remotely post the information to the server
		$link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_phones/'.$id.'.json';

		$data = null;
		$httpSocket = new HttpSocket();
		$data['Phone']['name'] = 'Updated Phone Name';
		$data['Phone']['manufacturer'] = 'Updated Phone  Manufacturer';
		$data['Phone']['name'] = 'Updated Phone  Description';
		$response = $httpSocket->put($link, $data );
		$this->set('response_code', $response->code);
		$this->set('response_body', $response->body);

		$this -> render('/Client/request_response');
	}

	public function request_add(){

		// remotely post the information to the server
		$link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_phones.json';

		$data = null;
		$httpSocket = new HttpSocket();
		$data['Phone']['name'] = 'New Phone';
		$data['Phone']['manufacturer'] = 'New Phone Manufacturer';
		$data['Phone']['name'] = 'New Phone Description';
		$response = $httpSocket->post($link, $data );
		$this->set('response_code', $response->code);
		$this->set('response_body', $response->body);

		$this -> render('/Client/request_response');
	}

	public function request_delete($id){

		// remotely post the information to the server
		$link =  "http://" . $_SERVER['HTTP_HOST'] . $this->webroot.'rest_phones/'.$id.'.json';

		$data = null;
		$httpSocket = new HttpSocket();
		$response = $httpSocket->delete($link, $data );
		$this->set('response_code', $response->code);
		$this->set('response_body', $response->body);

		$this -> render('/Client/request_response');
	}
}

```

**Bước 7: Demo**

- ![4.PNG](/uploads/bdffc531-b53d-40a1-b978-b8a6f66133d5.png)

    Chọn add phone

- ![5.PNG](/uploads/62f208dd-bacf-46f5-89a4-f6eadb30aec3.png)

**Link tham khảo:** http://book.cakephp.org/2.0/en/development/rest.html
0