Enhance PHP Applications with Custom Attributes

Leverage PHP 8 attributes to build robust and maintainable routing and validation systems.

Auriga Aristo
Indonesian Developer

--

Photo by Peter Masełkowski on Unsplash

If you are a non-member, you can read this story through the link here.

When working with PHP, we might find code that looks like #[Attribute()]. What is this, and how does this feature affect our code?

Since PHP 8, the language has provided a way to add metadata to classes, methods, properties, and parameters. It’s called PHP Attributes. This metadata can be used for various purposes, such as configurations, documentation, or runtime behavior alteration. Attributes are defined using the #[…] syntax and can be read via reflection.

Usage of PHP Attributes

Routing in Web Frameworks

You can use attributes to define routes directly in your controller classes, making your code more readable and easier to maintain.

#[Route('/home')]
class HomeController {
#[Route('/index')]
public function index() {
// ...
}
}

Validation

Attributes can specify validation rules for properties or parameters, making it easier to enforce data integrity.

--

--

Auriga Aristo
Indonesian Developer

4+ years in Backend Developer | PHP, Java/Kotlin, MySQL, Golang | New story every week