Attributes in PHP

Attributes offer the ability to add structured, machine-readable metadata information on declarations in code: Classes, methods, functions, parameters, properties and class constants can be the target of an attribute. The metadata defined by attributes can then be inspected at runtime using the Reflection APIs. Attributes could therefore be thought of as a configuration language embedded directly into code.

Example:

<?php

// Define an interface for action handlers
interface ActionHandler
{
    // Method to execute the action
    public function execute();
}

// Define a custom attribute named SetUp
#[Attribute]
class SetUp {}

// Implement the CopyFile class which implements the ActionHandler interface
class CopyFile implements ActionHandler
{
    // Properties to store file name and target directory
    public string $fileName;
    public string $targetDirectory;

    // Define a method annotated with the SetUp attribute to check if the file exists
    #[SetUp]
    public function fileExists()
    {
        // Check if the file exists
        if (!file_exists($this->fileName)) {
            throw new RuntimeException("File does not exist");
        }
    }

    // Define a method annotated with the SetUp attribute to check if the target directory exists
    #[SetUp]
    public function targetDirectoryExists()
    {
        // Check if the target directory exists, create it if it doesn't
        if (!file_exists($this->targetDirectory)) {
            mkdir($this->targetDirectory);
        } elseif (!is_dir($this->targetDirectory)) {
            throw new RuntimeException("Target directory $this->targetDirectory is not a directory");
        }
    }

    // Implement the execute method required by the ActionHandler interface
    public function execute()
    {
        // Copy the file to the target directory
        copy($this->fileName, $this->targetDirectory . '/' . basename($this->fileName));
    }
}

// Function to execute an action handler
function executeAction(ActionHandler $actionHandler)
{
    // Get the reflection object of the action handler
    $reflection = new ReflectionObject($actionHandler);

    // Iterate through each method of the action handler
    foreach ($reflection->getMethods() as $method) {
        // Get all attributes applied to the current method
        $attributes = $method->getAttributes(SetUp::class);

        // If the method has SetUp attribute(s)
        if (count($attributes) > 0) {
            // Get the name of the method
            $methodName = $method->getName();

            // Call the method
            $actionHandler->$methodName();
        }
    }

    // Execute the action
    $actionHandler->execute();
}

// Instantiate a CopyFile action handler
$copyAction = new CopyFile();
$copyAction->fileName = "/tmp/foo.jpg";
$copyAction->targetDirectory = "/home/user";

// Execute the action
executeAction($copyAction);

source: https://www.php.net/manual/en/language.attributes.overview.php

Also we can pass parameters to attributes:

class HomeController extends Controller
{
    #[Route(path: '/')]
    public function index(): void
    {
        $this->render('Home');
    }
}

GitHub Repo For Example Project

https://github.com/b1ink0/PHP-Learning-Projects/tree/php-attributes

«
»

Leave a Reply

Your email address will not be published. Required fields are marked *