Hướng dẫn can i build api with php? - tôi có thể xây dựng api với php không?

Trong hướng dẫn này, tôi sẽ dạy bạn cách xây dựng API REST đơn giản với PHP và MySQL.

REST đã trở thành tiêu chuẩn thực tế khi tiếp xúc dữ liệu thông qua API và xây dựng các dịch vụ web. Trên thực tế, hầu hết các ứng dụng web ngày nay truy cập và hiển thị dữ liệu thông qua API REST. Với sự phổ biến của các khung phía trước có thể tiêu thụ API REST một cách dễ dàng, nó sẽ luôn luôn là một điểm cộng cho bạn nếu ứng dụng web của bạn phơi bày các API REST.

Trong bài viết này, chúng tôi sẽ xây dựng một ứng dụng demo đơn giản, cho phép bạn tìm nạp danh sách người dùng từ cơ sở dữ liệu MySQL thông qua điểm cuối còn lại.

Thiết lập bộ xương

Trong phần này, chúng tôi sẽ đi qua cấu trúc dự án.

Hãy để một cái nhìn về cấu trúc sau.

├── Controller
│   └── Api
│       ├── BaseController.php
│       └── UserController.php
├── inc
│   ├── bootstrap.php
│   └── config.php
├── index.php
└── Model
    ├── Database.php
    └── UserModel.php

Hãy để cố gắng hiểu cấu trúc dự án.

  • index.php: điểm nhập của ứng dụng của chúng tôi. Nó sẽ hoạt động như một bộ điều khiển phía trước của ứng dụng của chúng tôi.: the entry-point of our application. It will act as a front-controller of our application.
  • Inc/config.php: Giữ thông tin cấu hình của ứng dụng của chúng tôi. Chủ yếu, nó sẽ giữ thông tin cơ sở dữ liệu.: holds the configuration information of our application. Mainly, it will hold the database credentials.
  • Inc/bootstrap.php: Được sử dụng để bootstrap Ứng dụng của chúng tôi bằng cách bao gồm các tệp cần thiết.: used to bootstrap our application by including the necessary files.
  • Model/Database.php: Lớp truy cập cơ sở dữ liệu sẽ được sử dụng để tương tác với cơ sở dữ liệu MySQL cơ bản.: the database access layer which will be used to interact with the underlying MySQL database.
  • Model/usermodel.php: tệp mô hình
    $CREATE DATABASE rest_api_demo;
    2 thực hiện các phương pháp cần thiết để tương tác với bảng người dùng trong cơ sở dữ liệu MySQL.
    : the
    $CREATE DATABASE rest_api_demo;
    2 model file which implements the necessary methods to interact with the users table in the MySQL database.
  • Trình điều khiển/API/Basecontroll.php: Một tệp bộ điều khiển cơ sở chứa các phương thức tiện ích chung.: a base controller file which holds common utility methods.
  • Trình điều khiển/API/UserControll.php: Tệp điều khiển
    $CREATE DATABASE rest_api_demo;
    2 chứa mã ứng dụng cần thiết để giải trí các cuộc gọi API REST.
    : the
    $CREATE DATABASE rest_api_demo;
    2 controller file which holds the necessary application code to entertain REST API calls.

Vì vậy, đó là thiết lập cơ bản mà chúng tôi sẽ thực hiện trong phần còn lại của bài đăng.

Tạo một cơ sở dữ liệu và các lớp mô hình

Trong phần này, chúng tôi sẽ tạo một cơ sở dữ liệu và bảng người dùng. Chúng tôi cũng sẽ tạo ra các lớp mô hình cần thiết sẽ được sử dụng để tìm nạp người dùng từ cơ sở dữ liệu.

Tạo cơ sở dữ liệu và bảng người dùng

Tạo cơ sở dữ liệu

$CREATE DATABASE rest_api_demo;
4 bằng cách thực thi lệnh sau trong thiết bị đầu cuối MySQL của bạn. (Truy cập cái này với lệnh
$CREATE DATABASE rest_api_demo;
5 từ dòng lệnh.)

$CREATE DATABASE rest_api_demo;

Bạn cũng có thể sử dụng một công cụ như phpmyadmin nếu bạn thích làm việc với cơ sở dữ liệu của mình theo cách đó.

Khi cơ sở dữ liệu

$CREATE DATABASE rest_api_demo;
4 được tạo, hãy tiếp tục và tạo bảng
$CREATE DATABASE rest_api_demo;
7 bằng cách chạy các câu lệnh sau.

$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Điều đó sẽ tạo bảng

$CREATE DATABASE rest_api_demo;
7 trong cơ sở dữ liệu
$CREATE DATABASE rest_api_demo;
4. Bạn cũng sẽ muốn điền vào bảng này với một vài bản ghi giả cho mục đích thử nghiệm. Chèn một vài hồ sơ, và bạn tốt để đi!

Tạo các lớp mô hình

Trong phần này, chúng tôi sẽ tạo ra các lớp mô hình cần thiết.

Tạo tệp mô hình/cơ sở dữ liệu.php với các nội dung sau.Model/Database.php file with the following contents.

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}

Đây là lớp lớp truy cập cơ sở dữ liệu, cho phép chúng tôi thiết lập kết nối với cơ sở dữ liệu MySQL. Ngoài thiết lập kết nối, nó còn chứa các phương thức chung như

$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
0 và
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
1 cho phép chúng tôi chọn các bản ghi từ cơ sở dữ liệu. Chúng tôi đã giành chiến thắng sử dụng lớp
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
2 trực tiếp; Thay vào đó, chúng tôi sẽ tạo các lớp mô hình tương ứng mở rộng lớp
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
2 để truy cập cơ sở dữ liệu MySQL cơ bản.

Tiếp theo, hãy để Lừa tạo lớp mô hình/usermodel.php với các nội dung sau.Model/UserModel.php class with the following contents.

select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}

Điều quan trọng cần lưu ý là lớp

$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
4 mở rộng lớp ____22.

Ngoài ra, nó còn chứa phương thức

$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
6, cho phép chúng tôi chọn người dùng từ cơ sở dữ liệu MySQL. Nó bắt buộc phải vượt qua tham số
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
7, điều này đảm bảo rằng nó đã giành được tất cả các bản ghi cùng một lúc.

Tất nhiên, bạn có thể xác định nhiều phương thức hơn trong lớp

$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
4 theo yêu cầu của bạn. Chúng tôi sẽ giữ mọi thứ đơn giản trong bối cảnh của hướng dẫn này.

Vì vậy, bây giờ chúng tôi có các lớp cơ sở dữ liệu và mô hình của chúng tôi được thiết lập. Trong phần tiếp theo, chúng tôi sẽ thấy cách tạo bộ điều khiển và các tệp còn lại trong ứng dụng demo của chúng tôi.

Tạo các thành phần lớp ứng dụng

Trong phần này, chúng tôi sẽ tạo các tệp còn lại cần thiết cho ứng dụng demo của chúng tôi hoạt động.

Thư mục Incinc Directory

Đối với người mới bắt đầu, chúng tôi sẽ tạo các tệp cấu hình cần thiết.

Tạo tệp inc/config.php với các nội dung sau.inc/config.php file with the following contents.

Đảm bảo cập nhật tất cả các giá trị với các giá trị thực tế mà bạn sử dụng trong cài đặt của mình.

Tiếp theo, hãy tiếp tục và tạo tệp Inc/bootstrap.php với các nội dung sau.inc/bootstrap.php file with the following contents.

Đầu tiên, chúng tôi đã khởi tạo hằng số

$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
9 với root thư mục của ứng dụng. Theo cách này, chúng tôi có thể sử dụng hằng số
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
9 để chuẩn bị các đường dẫn tuyệt đối trong ứng dụng của chúng tôi. Tiếp theo, chúng tôi đã bao gồm tệp Config.php, lưu giữ thông tin kết nối cơ sở dữ liệu. Cuối cùng, chúng tôi đã bao gồm các tệp điều khiển và mô hình.config.php file, which holds the database connection information. Finally, we've included controller and model files.

Vì vậy, đó là nó để thiết lập các tệp phổ biến trong ứng dụng của chúng tôi.

Thư mục điều khiển

Trong phần này, chúng tôi sẽ triển khai các bộ điều khiển nắm giữ phần lớn logic ứng dụng của chúng tôi.

Tệp Basecontroll.phpBaseController.php File

Tạo tệp điều khiển/API/Basecontroll.php với các nội dung sau. Lớp

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
1 chứa các phương thức tiện ích được sử dụng bởi các bộ điều khiển khác.Controller/Api/BaseController.php file with the following contents. The
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
1 class contains the utility methods that are used by other controllers.

sendOutput('', array('HTTP/1.1 404 Not Found'));
    }

    /**
     * Get URI elements.
     * 
     * @return array
     */
    protected function getUriSegments()
    {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $uri = explode( '/', $uri );

        return $uri;
    }

    /**
     * Get querystring params.
     * 
     * @return array
     */
    protected function getQueryStringParams()
    {
        return parse_str($_SERVER['QUERY_STRING'], $query);
    }

    /**
     * Send API output.
     *
     * @param mixed  $data
     * @param string $httpHeader
     */
    protected function sendOutput($data, $httpHeaders=array())
    {
        header_remove('Set-Cookie');

        if (is_array($httpHeaders) && count($httpHeaders)) {
            foreach ($httpHeaders as $httpHeader) {
                header($httpHeader);
            }
        }

        echo $data;
        exit;
    }
}

Hãy để nhanh chóng đi qua tất cả các phương pháp lớp

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
1 một cách nhanh chóng.

Phương pháp

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
3 là một phương pháp ma thuật và nó được gọi là khi bạn cố gắng gọi một phương thức không tồn tại. Chúng tôi sử dụng cơ hội này để ném lỗi
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
4 khi ai đó cố gắng gọi một phương pháp mà chúng tôi đã thực hiện. Nếu điều này nghe có vẻ khó hiểu với bạn, đừng lo lắng, điều đó sẽ có ý nghĩa hơn khi chúng tôi kiểm tra ứng dụng của chúng tôi trong phần tiếp theo.

Tiếp theo, có phương thức

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
5, trả về một mảng các phân đoạn URI. Nó rất hữu ích khi chúng tôi cố gắng xác thực điểm cuối còn lại do người dùng gọi. Theo đó, có phương thức
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
6, trả về một mảng các biến chuỗi truy vấn được truyền cùng với yêu cầu đến.

Cuối cùng, có phương thức

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
7, được sử dụng để gửi phản hồi API. Chúng tôi sẽ gọi phương thức này khi chúng tôi muốn gửi phản hồi API cho người dùng.

Tệp usercontroll.phpUserController.php File

Tiếp theo, tạo tệp Bộ điều khiển/API/UserControll.php với các nội dung sau.Controller/Api/UserController.php file with the following contents.

getQueryStringParams();

        if (strtoupper($requestMethod) == 'GET') {
            try {
                $userModel = new UserModel();

                $intLimit = 10;
                if (isset($arrQueryStringParams['limit']) && $arrQueryStringParams['limit']) {
                    $intLimit = $arrQueryStringParams['limit'];
                }

                $arrUsers = $userModel->getUsers($intLimit);
                $responseData = json_encode($arrUsers);
            } catch (Error $e) {
                $strErrorDesc = $e->getMessage().'Something went wrong! Please contact support.';
                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
            }
        } else {
            $strErrorDesc = 'Method not supported';
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
        }

        // send output
        if (!$strErrorDesc) {
            $this->sendOutput(
                $responseData,
                array('Content-Type: application/json', 'HTTP/1.1 200 OK')
            );
        } else {
            $this->sendOutput(json_encode(array('error' => $strErrorDesc)), 
                array('Content-Type: application/json', $strErrorHeader)
            );
        }
    }
}

Điều quan trọng cần lưu ý là lớp

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
8 mở rộng lớp
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
1. Lý tưởng nhất, lớp này sẽ chứa các phương thức hành động được liên kết với các điểm cuối còn lại được xác định cho thực thể người dùng. Trong trường hợp của chúng tôi, ví dụ, điểm cuối REST
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
0 tương ứng với phương thức
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
1. Theo cách này, bạn cũng có thể xác định các phương thức khác cho các điểm cuối còn lại khác.

Phương thức

select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
1 được sử dụng để có được danh sách người dùng từ cơ sở dữ liệu MySQL. Nó chứa toàn bộ logic của điểm cuối REST
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
0.

Trong phương thức

select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
1, chúng tôi đã khởi tạo một vài biến như
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
5 và
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
6 ngay từ đầu. Tiếp theo, chúng tôi kiểm tra xem người dùng đã gọi điểm cuối
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
7 với phương thức
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
8; Nếu không, chúng tôi đã giành được quy trình tiếp tục. Cuối cùng, chúng tôi tạo đối tượng
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
4 và gọi phương thức
$use rest_api_demo;
$CREATE TABLE `users` (
  `user_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(60) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
  `user_status` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
6 để lấy danh sách người dùng từ cơ sở dữ liệu. Chúng tôi cũng đã sử dụng chức năng
1 để chuyển đổi một mảng thành đối tượng JSON trước khi nó được gửi cho người dùng.

Cuối cùng, chúng tôi đã sử dụng phương thức

connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
7 để gửi phản hồi JSON cho người dùng. Điều quan trọng cần lưu ý là giá trị tiêu đề loại nội dung phản hồi được đặt thành
3 vì chúng tôi gửi phản hồi JSON.

Tương tự, bạn cũng có thể xác định các phương thức khác cho các điểm cuối khác.

Tệp index.phpindex.php File

Tệp index.php là điểm nhập của ứng dụng của chúng tôi. Hãy để xem nó trông như thế nào.index.php file is the entry-point of our application. Let’s see how it looks.

{$strMethodName}();
?>

Đầu tiên, chúng tôi đã sử dụng các chức năng

4 và 
5 để khởi tạo các phân đoạn URI vào biến mảng 
6. Tiếp theo, chúng tôi xác nhận các phân đoạn URI. Cuối cùng, chúng tôi đã khởi tạo bộ điều khiển 
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
8 và gọi phương thức hành động tương ứng.

Với điều đó, chúng tôi đã tạo tất cả các tệp cần thiết trong ứng dụng Demo REST của chúng tôi. Trong phần tiếp theo, chúng tôi sẽ thấy cách gọi nó từ góc độ người dùng cuối.

Cách gọi API REST của chúng tôi

Trong phần này, chúng tôi sẽ thấy cách gọi ứng dụng demo của chúng tôi. Trong ứng dụng của chúng tôi, chúng tôi đã xây dựng một điểm cuối còn lại để có được danh sách người dùng.

Hãy cùng xem URL của điểm cuối của chúng ta trông như thế nào:

$CREATE DATABASE rest_api_demo;
0

Nếu bạn nhớ lại tệp index.php, chúng tôi đã kiểm tra xem biến

8 được đặt thành 
9. Ngoài ra, giá trị biến 
0 sẽ hoạt động như một tên phương thức. Trong trường hợp trên, biến 
0 được đặt thành 
2. Do đó, cuối cùng nó sẽ gọi phương thức 
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
1 của lớp
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
8.index.php file, we checked if the
8 variable is set to 
9. Also, the 
0 variable value would act as a method name. In the above case, the
0 variable is set to 
2. Thus, it would end up calling the 
select("SELECT * FROM users ORDER BY user_id ASC LIMIT ?", ["i", $limit]);
    }
}
1 method of the
connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE_NAME);
    	
            if ( mysqli_connect_errno()) {
                throw new Exception("Could not connect to database.");   
            }
        } catch (Exception $e) {
            throw new Exception($e->getMessage());   
        }			
    }

    public function select($query = "" , $params = [])
    {
        try {
            $stmt = $this->executeStatement( $query , $params );
            $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);				
            $stmt->close();

            return $result;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }
        return false;
    }

    private function executeStatement($query = "" , $params = [])
    {
        try {
            $stmt = $this->connection->prepare( $query );

            if($stmt === false) {
                throw New Exception("Unable to do prepared statement: " . $query);
            }

            if( $params ) {
                $stmt->bind_param($params[0], $params[1]);
            }

            $stmt->execute();

            return $stmt;
        } catch(Exception $e) {
            throw New Exception( $e->getMessage() );
        }	
    }
}
8 class.

Đầu ra sẽ trông như thế này:

$CREATE DATABASE rest_api_demo;
1

Như bạn có thể thấy, nó trả về danh sách người dùng dưới dạng đối tượng JSON. Ngoài ra, nếu có bất kỳ lỗi ứng dụng nào, nó sẽ được trả về dưới dạng đối tượng JSON cũng như cho mục đích gỡ lỗi.

Sự kết luận

Hôm nay, chúng tôi đã thảo luận về cách bạn có thể xây dựng một ứng dụng REST với PHP và MySQL. Đối với mục đích trình diễn, chúng tôi đã tạo một ứng dụng demo cho phép bạn tìm nạp danh sách người dùng từ cơ sở dữ liệu MySQL thông qua API REST.

Bạn có thấy bài đăng này hữu ích?

Hướng dẫn can i build api with php? - tôi có thể xây dựng api với php không?

Kỹ sư phần mềm, FSPL, Ấn Độ

Tôi là một kỹ sư phần mềm chuyên nghiệp, và tôi đã thực hiện kỹ thuật khoa học máy tính. Đã khoảng 14 năm tôi đã làm việc trong lĩnh vực phát triển trang web và công nghệ nguồn mở. Chủ yếu, tôi làm việc trên các dự án và khung dựa trên PHP và MySQL. Trong số đó, tôi đã làm việc trên các khung web như Codeignitor, Symfony và Laravel. Ngoài ra, tôi cũng có cơ hội làm việc trên các hệ thống CMS khác nhau như Joomla, Drupal và WordPress và các hệ thống thương mại điện tử như Magento, Opencart, WooC Commerce và Drupal Commerce. Tôi cũng muốn tham dự các hội nghị công nghệ cộng đồng, và là một phần của điều đó, tôi đã tham dự Hội nghị Thế giới Joomla 2016 được tổ chức tại Bangalore (Ấn Độ) và 2018 Drupalcon được tổ chức tại Mumbai (Ấn Độ). Ngoài ra, tôi thích đi du lịch, khám phá những địa điểm mới và nghe nhạc!

Chúng ta có thể tạo API trong PHP không?

Các bước để tạo API REST: Tạo một cơ sở dữ liệu và bảng DB. Thiết lập kết nối cơ sở dữ liệu. Tạo tệp API REST. Tạo tệp chỉ mục hoặc HTML.Create a database and DB table. Establish database connection. Create a REST API file. Create index or HTML file.

PHP có tốt cho API không?

Có nhiều khung PHP có thể được sử dụng để tạo API REST. Bên cạnh những gì tôi đã đề cập ở trên, có một số khung Php phổ biến khác. Laravel, Symfony, Codeigniter, YII, CakePHP và những người khác đều có thể tạo API REST. Tùy thuộc vào nhu cầu của bạn, bất cứ ai trong số các khung đó có thể là tốt nhất cho bạn.. Besides what I've mentioned above, there are several other popular PHP frameworks. Laravel, Symfony, CodeIgniter, Yii, CakePHP, and others can all create REST APIs. Depending on your needs, anyone of those frameworks may be best for you.

Nền tảng nào là tốt nhất để phát triển API?

9 Nền tảng quản lý API tốt nhất..
Nền tảng quản lý API hàng đầu. Dell Boomi. ....
Swaggerhub. Swaggerhub là một nền tảng quản lý API để các nhóm thúc đẩy kỷ luật và tính nhất quán trong quá trình phát triển. ....
Akana: ....
3Scale: ....
Quản lý API CA: ....
Ứng dụng WSO2 Cloud: ....
IBM API Connect: ....
Mulesoft Anypoint:.

API Web PHP là gì?

API web là gì? API là viết tắt của giao diện lập trình ứng dụng. API Web là giao diện lập trình ứng dụng cho web. API trình duyệt có thể mở rộng chức năng của trình duyệt web. API máy chủ có thể mở rộng chức năng của máy chủ web.an application programming interface for the Web. A Browser API can extend the functionality of a web browser. A Server API can extend the functionality of a web server.

Tôi có thể tạo API của riêng mình không?

Tạo API Restful của riêng bạn có thể là một cách tuyệt vời để xây dựng một doanh nghiệp xung quanh dữ liệu bạn đã thu thập hoặc một dịch vụ bạn đã tạo hoặc nó chỉ có thể là một dự án cá nhân thú vị cho phép bạn học một kỹ năng mới.Dưới đây là danh sách 20 hướng dẫn về cách thiết kế API REST của riêng bạn!

Bạn có thể tạo ứng dụng với PHP không?

Bạn có thể không nghe hay không rằng bạn có thể sử dụng PHP cho phát triển ứng dụng Android của mình.Chúng tôi có thể sử dụng PHP làm back-end cho các ứng dụng Android của chúng tôi và tin tưởng tôi rằng họ làm việc hoàn hảo với nhau.Bất kỳ ứng dụng Android nào cần đăng nhập và đăng ký tài khoản đều có thể sử dụng hiệu quả PHP trên mặt sau của nó.Any Android app that needs account log-in and registration can efficiently utilize PHP on its back-end.