Best practise for code lists

General discussion on PHP
Post Reply
tors8146
Posts: 4
Joined: Mon May 12, 2014 11:02 pm

Best practise for code lists

Post by tors8146 » Wed Jan 21, 2015 6:52 pm

We often have a setup like the following code-to-display-text mapping below and treat $MAP_STATUS like a constant array.
Is this a good practise? One advantage is that the mapping is easy to find (top of file, close to constants).
  • Should we move the array into the statusName() function instead? This seems better and should work well for a translation if needed in the future.
  • Should we store the array in a configuration file instead? It really is a constant array at this point and we don't need to change the values. We don't even need a translation right now.

Code: Select all

class User {
    const STATUS__ACTIVE     = 100;
    const STATUS__TERMINATED = 101;
	
    protected static $MAP_STATUS= array(
        self::STATUS__ACTIVE     => 'Active',
        self::STATUS__TERMINATED => 'Terminated',
    );

    public function statusName($status){
        return self::$MAP_STATUS[$status];
    }
}

the 3781
Posts: 4
Joined: Wed Jan 28, 2015 12:06 pm

Re: Best practise for code lists

Post by the 3781 » Wed Mar 04, 2015 11:53 am

can we move the array into the statusName() function instead?
its seems better and should work well for a translation if used in future.
then its better idea
thanks,
The Cheesy Animation - 3D Architectural Rendering

tors8146
Posts: 4
Joined: Mon May 12, 2014 11:02 pm

Re: Best practise for code lists

Post by tors8146 » Thu Aug 20, 2015 7:18 pm

Like this?

Code: Select all

class User {
    const STATUS__ACTIVE     = 100;
    const STATUS__TERMINATED = 101;

    public function statusName($status){
		static $map= array(
			self::STATUS__ACTIVE     => 'Active',
			self::STATUS__TERMINATED => 'Terminated',
		);
        return map[$status];
    }
}

Post Reply