Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP version of ASP.NET/C# property attribute class

Is there such a thing?

I'd like to do something like this in PHP but I can't see how to do it from the PHP docs:

public class User : ValidationBase
{  
  [NotNullOrEmpty(Message = "Please enter a user name.")] 
  public string UserName { get; set; } 
}

What I'm looking for is the PHP equivalent of an ASP.NET/C# property attribute, which in the above example is signified by the [NotNullOrEmpty(Message = "Please enter a user name.")] line above the property declaration.

like image 774
Stepppo Avatar asked Dec 22 '09 15:12

Stepppo


People also ask

What is ASP.NET PHP?

ASP.NET is a paid Microsoft provided web application framework, whereas PHP is a server-side scripting language that is open source. ASP.NET is better suited for large and medium-sized organizations, whereas PHP is better equipped to serve start-up and small-sized organizations.

Is PHP and C# similar?

C# has its roots in the C family of languages and will be immediately familiar to C, C++, Java, and JavaScript programmers. On the other hand, PHP is detailed as "A popular general-purpose scripting language that is especially suited to web development".

Which is faster PHP or ASP?

ASP.NET performs comparatively faster than PHP; because compiled languages are usually faster than interpreted languages.


2 Answers

PHP has no built-in mechanism for declaring attributes, but it is possible to simulate this behavior using some custom code. The basic idea is to place your metadata in a comment block, and then write a class that parses that comment block. This is less convenient than C# because you need to ensure that your comment "attributes" are formatted properly, but it works.

Here is an example of how to do this: http://web.archive.org/web/20130302084638/http://interfacelab.com/metadataattributes-in-php/

like image 93
Andy Wilson Avatar answered Sep 28 '22 14:09

Andy Wilson


The accepted answer from Andy Wilson links to pages which are no longer available. I managed to get to the page itself through http://web.archive.org/web/20130116184636/http://interfacelab.com/metadataattributes-in-php/ but the code download the author refers to is a dead link too.

However I've since found a great implementation of PHP Annotations here: https://github.com/mindplay-dk/php-annotations

The only downside I've found so far is that is relies on your file names and class names being the same and of the same case which with Code Igniter they aren't but once I'd worked this out I soon had it all working and of course this limitation wouldn't affect all implementations.

like image 39
Dazz Knowles Avatar answered Sep 28 '22 16:09

Dazz Knowles