Skip to content

PlusMagi's Blog By Pitt Phunsanit

Plus emotional magic to the knowledge of logic.

  • About’s Pitt
Close Button
PlusMagi's Blog By Pitt Phunsanit AI,API,architecture,Backend,computer science,Laravel,Programming,Programming Language PHP: Attributes

PHP: Attributes

2008-04-022008-04-02| phunsanitphunsanit| 0 Comment | 10:00
Categories:
  • AI
  • API
  • architecture
  • Backend
  • computer science
  • Laravel
  • Programming
  • Programming Language

PHP Attributes (หรือที่หลายคนคุ้นเคยในชื่อ “Annotations” จากภาษาอื่น) คือฟีเจอร์ที่ถูกเพิ่มเข้ามาตั้งแต่ PHP 8.0 มันคือการใส่ Metadata (ข้อมูลที่อธิบายข้อมูล) ให้กับโครงสร้างของโค้ด ไม่ว่าจะเป็น คลาส, เมธอด, ฟังก์ชัน, พร็อพเพอร์ตี้ หรือแม้กระทั่งพารามิเตอร์ โดยข้อมูลเหล่านี้จะไม่ส่งผลต่อการทำงานของโค้ดโดยตรง แต่เราสามารถดึงมาใช้ตรวจสอบหรือเปลี่ยนแปลงพฤติกรรมของโปรแกรมได้ผ่าน Reflection API

ก่อนหน้า PHP 8.0 เรามักจะใช้ Docblocks (คอมเมนต์ / ... */) ในการเขียนอธิบาย ซึ่งมีข้อเสียคือระบบไม่ได้ตรวจสอบไวยากรณ์ (Syntax) และดึงข้อมูลไปใช้ค่อนข้างยาก แต่พอมี Attributes ทุกอย่างก็กลายเป็นเรื่องที่ถูกต้องตามโครงสร้างของภาษา และใช้งานง่ายขึ้นมากครับ


💡 โครงสร้างและไวยากรณ์ (Syntax)

การประกาศใช้ Attribute ใน PHP จะใช้เครื่องหมาย #[ ] วางไว้เหนือสิ่งที่เราต้องการกำหนด Metadata

#[AttributeName]
class MyClass {
    #[AttributeName]
    public string $myProperty;

    #[AttributeName]
    public function myMethod(#[AttributeName] $argument) {}
}

นอกจากนี้เรายังสามารถส่งค่า (Arguments) เข้าไปใน Attribute ได้เหมือนกับการเรียกใช้งานฟังก์ชันปกติเลยครับ

#[JoinTable(name: "users_roles")]
#[Column("username", type: "string", length: 50)]

🛠️ วิธีการสร้างและใช้งาน Attributes (Step-by-Step)

ลองมาดูตัวอย่างการสร้างระบบ Validation ง่ายๆ ด้วย Attributes กันครับ เพื่อให้เห็นภาพการทำงานจริง


1. ประกาศคลาสสำหรับ Attribute

การสร้าง Attribute ก็คือการสร้างคลาสธรรมดา แต่เราต้องใส่ #[Attribute] ไว้บนหัวคลาส เพื่อบอกให้ PHP รู้ว่าคลาสนี้จะถูกนำไปใช้เป็น Attribute นะ

<?php

#[Attribute(Attribute::TARGET_PROPERTY)] // กำหนดให้ใช้ได้เฉพาะกับ Property เท่านั้น
class StringLength {
    public function __construct(
        public int $min,
        public int $max
    ) {}
}

2. นำ Attribute ไปใช้งานในคลาสอื่น

ลองสร้างคลาส UserRegistration แล้วนำ #[StringLength] ที่เราสร้างเมื่อกี้ไปแปะไว้ที่พาสเวิร์ด

class UserRegistration {
    #[StringLength(min: 8, max: 20)]
    public string $password;

    public function __construct(string $password) {
        $this->password = $password;
    }
}

3. อ่านค่า Metadata ด้วย Reflection API

นี่คือขั้นตอนสำคัญ เพราะถ้าเราไม่ใช้ Reflection API มาอ่านค่า ตัว Attribute ก็จะอยู่เฉย ๆ ไม่มีผลอะไรครับ

function validate($object) {
    $reflection = new ReflectionClass($object);
    
    // วนลูปดู Property ทั้งหมดในคลาส
    foreach ($reflection->getProperties() as $property) {
        // ดึง Attribute ชื่อ StringLength ออกมา
        $attributes = $property->getAttributes(StringLength::class);
        
        foreach ($attributes as $attribute) {
            // แปลง Attribute กลับมาเป็น Instance ของคลาส StringLength เพื่อใช้งาน
            $validator = $attribute->newInstance();
            $value = $property->getValue($object);
            
            // ตรวจสอบเงื่อนไข
            if (strlen($value) < $validator->min || strlen($value) > $validator->max) {
                throw new Exception("Property {$property->getName()} ต้องมีความยาวระหว่าง {$validator->min} ถึง {$validator->max} ตัวอักษร");
            }
        }
    }
    echo "Validation ผ่านฉลุย! ✨";
}

// --- ทดลองใช้งาน ---
try {
    $user = new UserRegistration("12345"); // สั้นเกินไป (เงื่อนไขคือ 8-20)
    validate($user);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage(); 
    // ผลลัพธ์: Error: Property password ต้องมีความยาวระหว่าง 8 ถึง 20 ตัวอักษร
}

🎯 ประโยชน์ของการใช้ Attributes

  • Syntax Validation
    มีระบบตรวจไวยากรณ์ตั้งแต่ตอนเขียน (IDE ช่วยเตือนได้) ไม่เหมือน Docblock ที่เป็นแค่คอมเมนต์ตัวหนังสือธรรมดา
  • Performance
    อ่านค่าได้เร็วกว่าการไปคอย Parse คอมเมนต์ผ่าน Regex แบบสมัยก่อนมาก
  • Clean Code
    แยกส่วนของ Logic หลัก ออกจากส่วนที่เป็น Configuration หรือ Metadata อย่างชัดเจน
  • Framework Friendly
    ปัจจุบันเฟรมเวิร์กดัง ๆ อย่าง Symfony (เช่น Routing) หรือ Laravel และคลังไลบรารีอย่าง Doctrine ORM ต่างเปลี่ยนมาใช้ Attributes เป็นมาตรฐานหลักแล้ว

อ่านเพิ่มเติม

  • PHP: จาก 5 มา 8 ต้องปรับตัวอะไรบ้าง
  • PHP: .ini config อยู่หนใด
  • PHP: php-amqplib แบบต่อเนื่อง
Tags: Annotations, Attributes, backend, Clean Code, Configuration, core, Docblocks, Metadata, PHP, php 8.0, Reflection API

แนะแนวเรื่อง

PREVIOUS Previous post: เจาะลึก PHP Enums (Enumerations): ฟีเจอร์ที่ช่วยให้โค้ดสะอาดและปลอดภัยยิ่งขึ้น
NEXT Next post: PHP: Nullsafe Operator (?->)

Projects

  • Statement Columns Mapping Helper
  • PlusMagi Blocks
  • PlusMagi Site Search
  • PlusMagi Tags Reindex
  • jQuery Plus Repeater

Recent Posts

  • A-10 Thunderbolt II: ตำนานหมูป่าหุ้มเกราะ ผู้ครองน่านฟ้าสนับสนุนภาคพื้นดิน
  • เจาะลึก Lockheed Martin F-35 Lightning II: พลิกโฉมสงครามทางอากาศยุคที่ 5 และการประชันสมรรถนะของ 3 รุ่นย่อย
  • สถิติไร้พ่ายบนขอบอวกาศ: เจาะลึกตำนาน Lockheed SR-71 Blackbird
  • ย้อนรอย Lockheed Martin F-22 Raptor: ราชาแห่งการครองอากาศยุคที่ 5 ที่ไม่มีวันส่งออก
  • WordPress: วิธีเขียน SQL Query ค้นหา Classic Block และเนื้อหายุคเก่า

Archives

Categories

  • applied mathematics (302)
    • agriculture (20)
    • Astronomy (27)
    • Botany (93)
    • chemistry (42)
    • Cosmology (4)
    • Environmental Science (22)
    • physics (3)
    • statistics (2)
  • business (2,129)
    • Accounting (136)
    • Business Analysis (912)
    • collaboration (120)
    • Corporate Governance (4)
    • Finance (107)
    • Governance (10)
    • Marketing (67)
    • Operations Management (2)
    • Real Estate (31)
    • risk management (2)
  • computer science (3,067)
    • AI (494)
    • Biology (211)
      • Environment (54)
    • Cloud Computing (1,265)
    • Computer Engineering (29)
    • Data Transformation (208)
    • Data Visualization (66)
    • information retrieval (2)
    • Information Science (37)
    • Information Technology (88)
    • library science (3)
    • Mathematics (47)
    • technology (9)
    • เทคโนโลยี (194)
  • Design (337)
    • UX/UI (53)
  • engineering (1,293)
    • architecture (1,045)
    • Automotive (59)
    • Bioengineering (34)
    • Building Engineering (135)
    • Civil Engineering (94)
    • Electrical Engineering (10)
    • Mechanical Engineering (3)
    • Safety Engineering (3)
    • transportation (3)
    • urban planning (9)
  • Humanities (1,130)
    • Academia (709)
    • Archaeology (28)
    • art (160)
    • Communication (158)
    • Culture (183)
    • Education (4)
    • history (115)
    • Linguistics (20)
    • Literature (101)
    • media studies (3)
    • military history (3)
    • Religion (4)
    • social science (4)
    • Sociology (2)
    • Spirituality (2)
  • Law (314)
  • Life (2,162)
    • Accessibility (32)
    • Cartoon (146)
    • D.I.Y (78)
    • Health (203)
      • Safety (127)
    • Mindset (311)
    • Movies (200)
    • Philosophy (246)
    • Psychology (1,377)
      • Behavioral Science (1,249)
      • Cognitive Science (501)
    • Sci-Fi (93)
    • Tips and Tricks (59)
    • พุทธ (7)
  • management (875)
    • knowledge management (278)
      • Documentation (81)
    • productivity (5)
    • Project Management (16)
    • strategy (4)
  • Network (437)
    • IOT (27)
    • Nginx (27)
  • Operating Systems (613)
    • Linux (206)
    • macOS (151)
      • Homebrew (25)
    • Shell Script (45)
      • Oh My ZSH (5)
    • Windows (98)
      • PowerShell (25)
  • Programming (2,853)
    • .NET (199)
      • .NET Core EF (12)
      • C# (147)
    • API (838)
      • REST (8)
    • Database (705)
      • MariaDB (34)
      • MySql (66)
      • Oracle Database (24)
      • PostgreSQL (21)
      • RDBMS (55)
      • SQL Server (76)
        • T-SQL (26)
    • Programming Language (7)
    • Programming Languages (391)
      • Java (96)
      • PHP (238)
      • Python (13)
      • Rust (31)
    • Software Architecture (9)
    • Software Engineering (84)
    • System Analyst (SA) (66)
    • system architecture (5)
    • system design (7)
    • System Modeling (3)
    • Systems Programming (2)
    • Testing (140)
      • Automated Testing (127)
    • Web (2,566)
      • Apache HTTP Server (58)
      • Backend (2,363)
        • Laravel (54)
        • Spring Boot (15)
      • Frontend (382)
        • Angular (16)
        • CSS (67)
        • JavaScript (194)
        • jQuery (57)
        • Tabulator (24)
        • Tailwind CSS (4)
        • Vue.js (6)
      • WordPress (40)
  • SecDevOps (1,106)
    • automation (496)
    • CI/CD (349)
    • Docker (119)
    • GIT (56)
    • Hardware (84)
    • SVN (6)
    • system (248)
      • System Administration (37)
  • Security (629)
    • Authentication (248)
    • Cryptography (43)
    • Cybersecurity (349)
  • Uncategorized (1)

Sirat WordPress Theme By VWThemes

Scroll Up
Go to mobile version