Sensible Namespaces in PHP

Common convention for namespaces in PHP is to start with Vendor\Package, capitalized (CamelCase StudlyCaps) with “vendor” and “package” analogous to the composer package name.

There is a bad habit I see often, probably coming from the ZF1 and Pear days, where every word in the class name is a new sub namespace (and a new subdirectory), or child classes are moved into a namespace with the name of the parent class. All this is leading to deeply nested namespaces and class names that have no meaning without their namespace.

Examples from Zend Framework 1 (pseudo namespaces):

  • Zend_Db_Table_Row_Abstract an abstract base class for Zend_Db_Table_Row, representing a database table row. There are also Zend_Db_Table and Zend_Db.
  • Zend_Pdf_FileParser_Font_OpenType_TrueType a parser for true type font files. The class extends Zend_Pdf_FileParser_Font_OpenType which extends Zend_Pdf_FileParser_Font which extends Zend_Pdf_FileParser

And a current example from Magento 2:

  • Magento\Catalog\Model\Product\Option\Type\File\Validator – A validator for product options of the type “file”

Continue reading “Sensible Namespaces in PHP”