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

2022-11-202022-11-20| 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, Clean Code, Configuration, Docblocks, Metadata, PHP, php 8.0, Reflection API

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

PREVIOUS Previous post: Network Architecture: BGP (Border Gateway Protocol) & Autonomous Systems (AS) โครงสร้างเน็ตระดับโลก
NEXT Next post: PHP Match Expression: มาแทน Switch Case

Projects

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

Recent Posts

  • อธิบายการใช้ Range Types และ GiST Index ใน PostgreSQL เพื่อแก้ปัญหา Range Query สองคอลัมน์
  • เทียบ Database GUI (DBeaver, DBX, DataGrip, Navicat)
  • ทำความรู้จักกับ dbx (getdbx.com): Database Client ยุคใหม่ที่ออกแบบมาเพื่อ Developer
  • Vorsan: แอปสารพัดประโยชน์ที่คนใช้ Mac ควรมีติดเครื่อง
  • Apple แต่งตั้ง จอห์น เทอร์นัส (John Ternus) ขึ้นเป็น CEO โดยไม่ใช่ โจนี ไอฟ์ (Jony Ive)

Archives

Categories

  • .net core (47)
  • Accessibility (5)
  • Accounting (64)
  • Action Genre (2)
  • agriculture (3)
  • applied mathematics (63)
  • Archaeology (3)
  • art (95)
  • Artificial Intelligence (97)
  • Astronomy (4)
  • Automotive (9)
  • Automotive History (4)
  • Bioengineering (5)
  • Botany (1)
  • business (1,355)
    • Business Analysis (606)
    • Finance (42)
    • Real Estate (27)
  • cd (148)
  • chemistry (16)
  • ci (151)
  • Civil Engineering (28)
  • CMS (49)
  • collaboration (120)
  • Comics (1)
  • Command Line Interface (26)
  • Communication (157)
  • Communication Studies (1)
  • Community Governance (1)
  • Community Management (1)
  • compliance (1)
  • Computer Engineering (4)
  • Computer Hardware (63)
  • computer science (2,115)
    • AI (395)
    • Biology (126)
      • Environment (34)
    • Cloud Computing (478)
    • Data Visualization (65)
    • Mathematics (46)
  • construction (1)
  • Consumer Electronics (1)
  • container (63)
  • Content Creation (1)
  • Corporate Governance (3)
  • Corporate Law (1)
  • Cosmology (2)
  • Culture (151)
  • data engineering (5)
  • data management (5)
  • Data Modeling (1)
  • Data Privacy (80)
  • data science (7)
  • Data Transformation (171)
  • Database Management (6)
  • Database Systems (3)
  • Design (333)
    • UX/UI (45)
  • development (1)
  • devops (19)
  • DevOps Engineering (1)
  • Digital Electronics (1)
  • digital marketing (2)
  • digital technology (1)
  • disaster management (1)
  • e-learning (1)
  • Earth Science (1)
  • Ecology (1)
  • Education (4)
  • Electrical Engineering (4)
  • Electronics (4)
  • Electronics Engineering (3)
  • Embedded Systems (1)
  • engineering (1,156)
    • architecture (1,026)
    • Building Engineering (112)
  • Entertainment (1)
  • Entrepreneurship (1)
  • environmental (1)
  • Environmental Science (3)
  • Environmentalism (1)
  • Facility Management (1)
  • Fantasy Literature (1)
  • Film (2)
  • film studies (2)
  • Forensic Science (1)
  • front-end development (2)
  • Frontend Development (3)
  • Geographical Information System (1)
  • Geology (1)
  • Governance (6)
  • Grammar (1)
  • graph theory (1)
  • Hardware (5)
  • Health (159)
    • Safety (127)
  • health and safety (1)
  • health and wellness (1)
  • Health Science (2)
  • Home Appliances (1)
  • Human Resources (1)
  • Human-Computer Interaction (1)
  • Humanities (669)
    • Academia (453)
    • history (113)
    • Linguistics (16)
    • Literature (98)
  • Information Architecture (1)
  • Information Management (1)
  • information retrieval (2)
  • Information Science (14)
  • information security (1)
  • Information Technology (3)
  • Insurance (1)
  • International Relations (1)
  • Internet of Things (2)
  • IT Operations (1)
  • landscape architecture (1)
  • Language Arts (1)
  • Law (302)
  • Law and Regulation (1)
  • Legal (1)
  • Legal Advice (1)
  • legal affairs (1)
  • Legal Compliance (3)
  • Legal Framework (1)
  • legal studies (2)
  • legal_affairs (1)
  • library science (2)
  • Life (1,603)
    • Cartoon (41)
    • D.I.Y (62)
    • Mindset (311)
    • Movies (58)
    • Philosophy (229)
    • Psychology (1,226)
      • Behavioral Science (817)
      • Cognitive Science (501)
    • Sci-Fi (65)
    • Tips and Tricks (32)
    • พุทธ (7)
  • Lifestyle (1)
  • logic (1)
  • logistics (1)
  • Machine Learning (2)
  • management (890)
    • knowledge management (295)
      • Documentation (98)
    • productivity (5)
    • Project Management (16)
    • strategy (4)
  • manufacturing technology (1)
  • Marketing (1)
  • Markup Languages (1)
  • Mechanical Engineering (3)
  • Media (1)
  • media studies (3)
  • medicine (1)
  • military history (2)
  • Military Technology (1)
  • Mystery (1)
  • Mythology (1)
  • Network (388)
    • IOT (24)
    • Nginx (26)
  • network security (1)
  • networking (56)
  • Neuroscience (1)
  • Object-Relational Mapping (1)
  • operating system (18)
  • Operating Systems (583)
    • Linux (208)
    • macOS (143)
      • Homebrew (25)
    • Shell Script (44)
      • Oh My ZSH (5)
    • Windows (99)
      • PowerShell (26)
  • Operations Management (2)
  • physics (3)
  • Plumbing Systems (1)
  • Pop Culture (1)
  • popular culture (1)
  • Process Improvement (1)
  • Process Management (1)
  • Process Modeling (1)
  • Product Design (1)
  • Programming (2,244)
    • .NET (121)
      • .NET Core EF (9)
      • C# (82)
    • API (539)
      • REST (8)
    • Database (701)
      • MariaDB (38)
      • MySql (69)
      • Oracle Database (24)
      • PostgreSQL (16)
      • RDBMS (55)
      • SQL Server (76)
        • T-SQL (26)
    • Programming Languages (368)
      • Java (95)
      • PHP (216)
      • Python (13)
      • Rust (31)
    • Software Architecture (7)
    • Software Engineering (66)
    • System Analyst (SA) (56)
    • Testing (127)
      • Automated Testing (113)
    • Web (1,570)
      • Apache HTTP Server (39)
      • Backend (1,295)
        • Laravel (54)
        • Spring Boot (15)
      • Frontend (309)
        • Angular (11)
        • CSS (67)
        • JavaScript (188)
        • jQuery (57)
        • Tabulator (24)
        • Tailwind CSS (4)
        • Vue.js (6)
      • WordPress (35)
  • Programming Language (5)
  • Property Law (2)
  • Property Management (3)
  • Public Health (2)
  • Public Policy (1)
  • quality assurance (1)
  • Religion (4)
  • risk management (2)
  • Safety and Security (1)
  • Safety Engineering (3)
  • Science (1)
  • Science Fiction (9)
  • SecDevOps (842)
    • automation (314)
    • CI/CD (137)
    • Docker (89)
    • GIT (58)
    • SVN (6)
    • system (232)
      • System Administration (22)
  • Security (497)
    • Authentication (129)
    • Cryptography (43)
    • Cybersecurity (304)
  • Sensory Technology (1)
  • SEO (1)
  • Server Infrastructure (1)
  • social science (4)
  • Sociology (2)
  • Software Design (1)
  • Software Development (6)
  • software development lifecycle (1)
  • Software Development Practices (1)
  • Software Licensing (3)
  • Software Testing (2)
  • Space Exploration (1)
  • Spirituality (2)
  • sports (1)
  • SQL (1)
  • statistics (2)
  • storage (1)
  • Storage Systems (1)
  • Storytelling (1)
  • structural engineering (1)
  • supply chain (1)
  • Supply Chain Management (1)
  • system architecture (2)
  • system design (6)
  • System Modeling (3)
  • Systems Modeling (1)
  • Systems Programming (2)
  • Technical Support (1)
  • technology (5)
  • Technology History (1)
  • transportation (1)
  • UI (3)
  • Uncategorized (671)
  • urban planning (7)
  • user experience (5)
  • User Experience Design (3)
  • User Interface Design (1)
  • UX Design (3)
  • Version Control (3)
  • Virtualization (1)
  • visualization (1)
  • Web Design (2)
  • web development (67)
  • Web Standards (2)
  • web technology (2)
  • wellness (2)
  • กฎหมาย (3)
  • การขนส่ง (1)
  • การดูแลรถ (1)
  • การตลาด (61)
  • การบำรุงรักษา (1)
  • การพัฒนาอสังหาริมทรัพย์ (1)
  • การเงิน (61)
  • ความปลอดภัยทางไซเบอร์ (30)
  • จราจร (1)
  • ธุรกิจ (174)
  • นวนิยายสืบสวน (1)
  • ผังเมือง (1)
  • วรรณกรรม (1)
  • สถาปัตยกรรม (1)
  • อสังหาริมทรัพย์ (2)
  • เทคโนโลยี (14)
  • เรื่องเล่า (1)

Sirat WordPress Theme By VWThemes

Scroll Up