Constants in Magento XML

Did you know you can use constants in Magento XML files? I hope you’re already in the habit of using references to class constants in your PHP code. (For example, comparing a string to \Magento\Sales\Model\Order::STATE_COMPLETE instead of hard-coding “complete”.) This a best practice for avoiding elusive problems sneaking into your application thanks to a simple misspelled string. As a rule of thumb, strings in our application code should only be used for arbitrary text, not values attached to functional logic.

While I’ve long used this pattern in PHP, it’s a little absurd how long I went on resorting to strings in my XML. If passing the “complete” status in the above example in, say, a list of arguments being provided to a type via di.xml, I’d simply bite the bullet and use the hard-coded value. Little did I know that I could have been using constants in XML all along:

And it works just as well in layout XML:

Just a little way we can make our custom code more stable!

Chris Nanninga

Director of Training and Development at SwiftOtter -@ChrisNanninga