Application Constants in Interfaces
July 25, 2008 8:20 pm PHPHere's a little trick I discovered the other day for passing application settings around in an object-oriented implementation. You can create an interface that defines any number of class constants, then any class you define that needs those constants needs only to implement that interface. For example:
<?php /** * Define constants for use in other classes */ interface Constants { const DB_HOST = 'localhost'; const DB_USER = 'username'; const DB_PASS = 'abc123xyzr'; const DB_NAME = 'test'; } /** * Database class based on MySQLi class */ class DB extends mysqli implements Constants { public function __construct() { parent::__construct( self::DB_HOST, self::DB_USER, self::DB_PASS, self::DB_NAME ); } }
The advantage of this over running some configuration script that sets the constants is that by implementing an interface, it becomes immediately visible that the class requires that interface. If on the other hand you depend on independently setting constants in an include file or such, then if you try to reuse a class that uses those constants, it will not be immediately obvious that they are needed until you start testing it in the new implementation.
The main limitation is that interfaces cannot have class variables, only constants. If you need application-wide variables for your object-oriented application, you'll either need to instantiate a class that has those variables and pass it to each object that needs it, use a singleton pattern class (which can have the same disadvantage of globals in that the fact that it is required can be hidden inside a class), or look into something like using a registry pattern class.
