Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Autoloading Classes ใน PHP

บทนำ

เพื่อใช้คลาสที่อยู่ในไฟล์ PHP อื่น เราสามารถ Include/Require ได้ แต่ PHP มีฟีเจอร์ Autoloading ที่โหลดคลาสอัตโนมัติเมื่อถูกใช้งาน (เช่น สร้างออบเจ็กต์) โดยไม่ต้อง Include โดยตรง ใช้ฟังก์ชัน spl_autoload_register() ลงทะเบียน Autoloader ได้หลายตัว PHP จะลองโหลดก่อนปล่อย Error

Syntax พื้นฐาน

spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

คลาสจะถูกโหลดจากไฟล์ .php ที่ตรงกับชื่อคลาส เมื่อถูกใช้ครั้งแรก

ตัวอย่าง Autoloading พื้นฐาน

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj = new test1();
$obj2 = new test2();
echo "objects of test1 and test2 class created successfully";
?>

ผลลัพธ์

objects of test1 and test2 class created successfully

ถ้าไม่พบไฟล์ .php จะเกิด Error:

Warning: include(): Failed opening 'test10.php' for inclusion
PHP Fatal error: Uncaught Error: Class 'test10' not found

Autoloading พร้อม Exception Handling

<?php
spl_autoload_register(function($className) {
    $file = $className . '.php';
    if (file_exists($file)) {
        echo "$file included\n";
        include $file;
    } else {
        throw new Exception("Unable to load $className.");
    }
});

try {
    $obj1 = new test1();
    $obj2 = new test10();  // ไม่มีไฟล์
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

ผลลัพธ์

test1.php included
Unable to load test10.

Best Practices: PSR-4 Autoloading

ในโปรเจกต์จริง ควรใช้ Composer กับ PSR-4 Standard:

// composer.json
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

แล้วรัน composer dump-autoload และ Include vendor/autoload.php ครั้งเดียว

ตัวอย่าง PSR-4 Structure

src/
├── Controller/
│   └── UserController.php  // namespace App\Controller;
└── Model/
    └── User.php            // namespace App\Model;

ข้อดีของ Composer Autoloader

  • Performance ดีกว่า (Class Map Caching)
  • Standard ระดับอุตสาหกรรม (PSR-4)
  • จัดการ Dependencies อัตโนมัติ
  • รองรับ Namespace Hierarchy

ข้อควรระวัง

  • Class Name ต้องตรงกับ Filename (Case-sensitive บน Linux)
  • Namespace ต้องตรงกับ Directory Structure
  • หลาย Autoloaders จะรันตามลำดับที่ Register