PHP yordamida sodda RESTful API yaratish

O'tgan maqolalarimdan birida Lumen Micro Framework da RESTful API dan foydalanish bo'yicha kichkina bir Tutorial tayyorlagandik, Endi esa PHP dasturlash tilining o'zida hech qanday Frameworklarsiz RESTful API ni qanday yaratish mumkinligi va undan foydalanishni ko'rib chiqamiz.

Ushbu tutorialda PHP REST bo'yicha, PHP bilan oddiy rial world RESTful API yaratishni o'rganamiz. Biz HTTP GET va HTTP POST metodlarini ko'rib chiqamiz va JSON-da ma'lumotlarni qaytarish uchun json_encode () ni ishlatamiz.

REST API, biz ushbu qo'llanmada yaratadigan asosiy maqsadimiz, keyingi qo'llanmalarda frontend qismni ham yaratishni ko'rib chiqamiz. Asosan frontend qism yaratish uchun zamonaviy JavaScript frameworklardan foydalaniladi, Masalan: VueJS, Angular, React va boshqalar.

Ushbu qo'llanmada EXIT, POST, PUT va DELETE ga o'xshash HTTP API metodlaridan foydalangan holda PHP ilova CRUD (Create, Read, Update and Delete) sini yaratamiz. Men API va RestFull nimaligi haqida to'xtalib o'tirishni joiz topmadim, shu sabab darrov ilovani yaratishga o'tamiz.

MySQL Database Design

Veb-API yaratish uchun siz server ma'lumotlar bazasida ma'lumotlarni saqlashingiz kerak. Ushbu qo'llanmada biz PHP Dasturlash tilib bilan eng ko'p ishlatiladigan ma'lumotlar bazasi tizimi bo'lgan MySQL RDMS (Relational Database Management System) dan foydalanamiz.

Dastlab nima qilamiz? Biz dastlab MB Struktura dizaynini yaratib olamiz. Agarda yaratish bo'yicha tajriba kam yoki oson tarzda yaratmoqchi bo'lsangiz Entity-Relationship Diagram dan foydalanishingiz mumkin.

Database (MB) bilan ishlaganlar yaxshi biladiki bizda jadvallarimiz | Birga-Bir, Birga-Ko'p, Ko'pga-Ko'p tarzida bog'lanishi mumkin. Demak quyidagi kabi bir diagramma yaratib olishimiz mumkin va MB strukturasini qilib olsak bo'ladi demak.

Bizda yuqoridagi jadvallar mavjud, Ushbu jadvalni tayyor internetdan oldim shu sabab siz ham bu jadvalni oldin ko'rgan bo'lishingiz mumkin. Yuqoridagi jadvallarni strukturasi yaratib olingach endi navbat MB da SQL jadvallarni yaratishga keldi.

SQL Database Tables Yaratish

Demak SQL jadvallarini yaratishni boshlaymiz.

CREATE TABLE `Product` (
  `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  `sku` varchar(255),
  `barcode` varchar(255),
  `name` varchar(100),
  `price` float,
  `unit` varchar(20),
  `quantity` float,
  `minquantity` float,
  `createdAt` datetime NOT NULL,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `familyid` int(11) NOT NULL,
  `locationid` int(11) NOT NULL
);
CREATE TABLE `Family` (
  `id` int(11)  UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  `reference` varchar(50),
  `name` varchar(100),
  `createdAt` datetime NOT NULL,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
  );
CREATE TABLE `Transaction` (
  `id` int(11)  UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  `comment` text,
  `price` float,
  `quantity` float,
  `reason` enum('New Stock','Usable Return','Unusable Return'),
  `createdAt` datetime NOT NULL,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `productid` int(11) NOT NULL
);
CREATE TABLE `Location` (
  `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  `reference` varchar(50),
  `description` text,
  `createdAt` datetime NOT NULL,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Jadvallarni yaratish uchun PhpMyAdmin dan foydalanishingiz mumkin. Yuqoridagi jadvallarni ko'chirib olib ishlatishingiz yoki o'zingizning ilovaga moslashtirishingiz mumkin.

PHP REST Project File Structur

Xo'sh endi ishimizning asosiy qismiga yaqinlashib qoldik. Endi File Structure ya'ni biz yaratayotgan fayllar va ular bilan ishlashni boshlaymiz. Barcha config fayllari config/ deb nomlangan folder da saqlaymiz va ishni boshlaymiz. MySQL baza bilan PHP ilovani bog'laymiz va konfiguratsiya ishlarini qilamiz.

MySQL Baza Bilan Aloqani Yaratish

Buning uchun config/ katalogida database.php file yaratib olamiz va quyidagi kodlarni kiritamiza.

<?php
class Database {
    private $host = "localhost"; //Localhost
    private $username = "root"; //Username
    private $password = "123456789"; //Password
    private $database = "rest_demo"; //Database Name
    public $connection;
    // Aloqani tashkil qilish
    public function getConnection(){
        $this->connection = null;
        try{
            $this->connection = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->database, $this->username, $this->password);
            $this->connection->exec("set names utf8");
        }catch(PDOException $exception){
            echo "Error: " . $exception->getMessage();
        }
        return $this->connection;
    }
}
?>

Endi biz ob'ektlarni (yoki ma'lumotlar bazasi jadvallarini) qamrab oladigan PHP Class yaratamiz. Har bir sinfda tegishli SQL jadvali nomini saqlaydigan kodlangan magistral bo'lib, Class ishlab chiqaruvchisi va jadval ustunlarini boshqa joylar bilan bog'laydigan aloqa klass namunasini amalga oshirib turadigan a'zolar o'zgaruvchisi saqlanadi. Har bir shaxs klassi shuningdek, tegishli jadval satrlarini yaratish, o'qish, yangilash va o'chirish uchun zarur bo'lgan CRUD operatsiyalarini ham qamrab oladi.

product.php Product Class

<?php
class Product{
    // Connection instance
    private $connection;
    // table name
    private $table_name = "Product";
    // table columns
    public $id;
    public $sku;
    public $barcode;
    public $name;
    public $price;
    public $unit;
    public $quantity;
    public $minquantity;
    public $createdAt; 
    public $updatedAt;
    public $family_id;
    public $location_id;
    public function __construct($connection){
        $this->connection = $connection;
    }
    //Yaratish Uchun Mo'ljallangan Funcsiya
    public function create(){
    }
    //R
    public function read(){
        $query = "SELECT c.name as family_name, p.id, p.sku, p.barcode, p.name, p.price, p.unit, p.quantity , p.minquantity, p.createdAt, p.updatedAt FROM" . $this->table_name . " p LEFT JOIN Family c ON p.family_id = c.id ORDER BY p.createdAt DESC";
        $stmt = $this->connection->prepare($query);
        $stmt->execute();
        return $stmt;
    }
    //Ma'lumotlarni Yangilash
    public function update()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'chirish
    public function delete()
    {
        //Bu yerda Funsiya A'zolari
    }
}

va

Transaction Class

<?php
class Transaction{
    // Connection instance
    private $connection;
    // table name
    private $table_name = "Transaction";
    // table columns
    public $id;
    public $comment;
    public $price;
    public $quantity;
    public $reason;
    public $createdAt; 
    public $updatedAt;
    public $product_id;
    public function __construct($connection){
        $this->connection = $connection;
    }
    //Ma'lumotlarni Yaratish
    public function create()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni Yangilash
    public function update()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'qish
    public function read()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'chirish
    public function delete()
    {
        //Bu yerda Funsiya A'zolari
    }  
}

Location Class

<?php
class Location{
    // Connection instance
    private $connection;
    // table name
    private $table_name = "Location";
    // table columns
    public $id;
    public $reference;
    public $description;
    public $createdAt; 
    public $updatedAt;
    public function __construct($connection){
        $this->connection = $connection;
    }
    //Ma'lumotlarni Yaratish
    public function create()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni Yangilash
    public function update()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'qish
    public function read()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'chirish
    public function delete()
    {
        //Bu yerda Funsiya A'zolari
    }  
}

Family Class

<?php
class Family{
    // Connection instance
    private $connection;
    // table name
    private $table_name = "Family";
    // table columns
    public $id;
    public $reference;
    public $name;
    public $createdAt; 
    public $updatedAt;
    public function __construct($connection){
        $this->connection = $connection;
    }
     //Ma'lumotlarni Yaratish
    public function create()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni Yangilash
    public function update()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'qish
    public function read()
    {
        //Bu yerda Funsiya A'zolari
    }
    //Ma'lumotlarni O'chirish
    public function delete()
    {
        //Bu yerda Funsiya A'zolari
    }  
}

Yuqorida Bizga kerakli Clas larni yaratib oldik. Siz bu kodlarni ko'chirib olib ishlatib ko'rishingiz mumkin.

API Yakuniy Qismlarini Yaratish

Xo'sh endi biz CRUD ga murojat qilamiz. Bizda to'rttda Katalog bor : products, transactions, families and locations va har bir katalog ichida create.php, read.php, update.php, delete.php. fayllarini yaratib olamiz.

HTTP GET API : products/read.php

HTTP GET metodidan foydalanamiz. Buning uchun products/read.php fayilini oching va quyidagi kodlarni kiriting.

<?php
header("Content-Type: application/json; charset=UTF-8");
include_once '../config/database.php';
include_once '../class/product.php';
$dbclass = new Database();
$connection = $dbclass->getConnection();
$product = new Product($connection);
$stmt = $product->read();
$count = $stmt->rowCount();
if($count > 0){
    $products = array();
    $products["body"] = array();
    $products["count"] = $count;
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        $p  = array(
            "id" => $id,
            "sku" => $sku,
            "barcode" => $barcode,
            "name" => $name,
            "price" => $price,
            "unit" => $unit,
            "quantity" => $quantity,
            "minquantity" => $minquantity,
            "createdAt" => $createdAt,
            "createdAt" => $createdAt,
            "updatedAt" => $updatedAt,
            "family_id" => $family_id,
            "location_id" => $location_id
        );
        array_push($products["body"], $p);
    }
    echo json_encode($products);
}
else {
    echo json_encode(
        array("body" => array(), "count" => 0);
    );
}
?>

HTTP POST API

Endi esa prodcut/create.php orqali POST metodidan foydalanib ko'ramiz.

<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
include_once '../config/Database.php';
include_once '../class/product.php';
$dbclass = new Database();
$connection = $dbclass->getConnection();
$product = new Product($connection);
$data = json_decode(file_get_contents("php://input"));
$product->name = $data->name;
$product->price = $data->price;
$product->description = $data->description;
$product->category_id = $data->category_id;
$product->created = date('Y-m-d H:i:s');
if($product->create()){
    echo '{';
    echo '"message": "Maxsulot Yaratildi."';
    echo '}';
}
else{
    echo '{';
    echo '"message": "Uzr Nimadir Yuz Berib Qoldi."';
    echo '}';
}
?>

Mana biz oddiy PHP yordamida sodda bo'lgan REST API yaratishni ko'rib chiqdik. Ushbu maqola bo'yicha tushunarsiz holatlar bo'lsa, yozib qoldirishingiz mumkin. Bu maqolada har bir detaliga juda ko'p etibor berib o'tirmadim va iloji boricha asosiy qismini ko'rsatishga harakat qildim, Bir necha kun ichida bu loyihani GitHub da to'liq holatda joylab qo'yishga harakat qilaman.

Xulosa.

Xo'sh biz nima ish qildik

- PHP va MySQL yordamida REST yaratdik.

- MB Diagrammasini tuzub oldik

- json_encode() dan foydalanishni bilib oldik.


Maqolada kamchilik va xatolar bo'lsa uzr so'rayman. Savol va takliflar kutib qolamiz....


Oktam

Muallif haqida

Yaqubov Oktam


Blogdagi so‘nggi maqolalar:


Fikrlar 3

abdujabbor1987
abdujabbor1987
Avtorga rahmat! ancha mehnat qilganingiz ko'rinib turibti. SOLID, KISS, DRY prinsiplarini va Design Patterns larni o'rganib chiqishizi tavsiya qilgan bo'lardim. bundan tashqari https://www.phptherightway.com/ da ham sizga ancha foydali bo'lishi mumkin bo'lgan narsalar bor. Rahmat!
Oktam
Oktam
Fikr uchun katta raxmat!) Bu yerdagi ma'lumotlar asosan boshlovchilar uchun, siz keltirgan Design Patterns, SOLID bu endi yuqoriroq levelda keltirgan ma'qul, tushunuvcchilarga soda qilish uchun shu yo'ldan foydalangandim...
Ilyosjon
Ilyosjon
Assalomu alaykum, juda ham foydali post bolibdi rahmat. Iloji bolsa ochiq APIlardan PHPda foydalanish haqida, ya'ni xavfsiz va optimal usulda foydalanish haqida ham maqola yozing. Rahmat.
Iltimos, fikr bildirish uchun saytga kiring yoki ro‘yxatdan o‘ting!