Using PHP traits to check class constants values

I’ve always looked for a ratio­nal expla­na­tion of using traits in PHP and I think I’ve found one. Let’s say we have a bunch of status codes which are set using constants. To remind: constants can also be set in inter­fa­ces (notice that constant inter­face pattern is consi­de­red as a bad practice).

We are writing an utils library and simply don’t trust users :-) It means we need to check if status codes set on object are valid. One way is to keep status codes as a range from number to number. Vali­da­ting is easy in that case. We’re simply check if status is in range. This is obvio­usly not common. We could use reflec­tion to list all class constants. And what if we have unre­la­ted hierar­chies of objects? We must dupli­cate some code. It’s against DRY prin­ci­ple. Trait to the rescue!

Take a look at my rich docu­men­ted gist and see how it works at the bottom of listing. Code is licen­sed under MIT License, so grab it and use it.

Podobne wpisy:

  1. 2 ways to check stream mimetype
  2. Func­tion over­lo­ading in JavaScript
  3. Creating EAN-13 barcode using Coffe­eScript and HTML5 Canvas
  4. Writing custom stream filters

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany.

Możesz użyć następujących tagów oraz atrybutów HTML-a: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <p> <pre lang="" line="" escaped=""> <q cite=""> <strike> <strong>