开发者

Best way to define an information array with a class

I have a database table which stores a "type" for a project which stores either a 1, 2 or 3 where:

1 = "Active" 2 = "Inactive" 3 = "Cancelled"

Currently, I store this mapping in an ar开发者_C百科ray in my config.php making it a global variable accessible from my whole application. It looks something like:

$project_types = array(1 => "Active", 2 => "Inactive", 3 => "Cancelled");

Now, I have a Project class, which has get_type() and set_type() methods to alter the integer value as expected. I want to have a get_type_name() method. Can anyone here explain what this method should look like? Currently, I have something that looks like this:

public function get_type_name() {
    global $project_types;
    return $project_types[$this->get_type()];
}

I the array above should somehow lay inside my Project class, but I'm just not sure what route to take.

Thanks.


Globals are bad, and in your case, creates an unnecessary dependency for your Project class.

The solution (one of many) is quite simple:
Create a class property that holds the types and do the lookup on it.

class Project {

    /**
     * @param array Holds human translations of project types.
     */
    protected $_types = array(
        1 => 'Active',
        2 => 'Inactive',
        3 => 'Cancelled',
    );

    /**
     * Get a human-readable translation of the project's current type.
     *
     * If a translation can't be found, it returns NULL.
     *
     * @return string|null
     */
    public function get_human_type() {
        $type = $this->get_type();
        return isset($this->_types[$type]) ? $this->_types[$type] : NULL;
    }

}


Personally, I'd declare it as a static class property, possibly using class constants for the different values:

class Project
{
    /**    constants */
    const STATUS_ACTIVE         = 'Active';
    const STATUS_INACTIVE       = 'Inactive';
    const STATUS_CANCELLED      = 'Cancelled';

    protected static $projectTypes    = array( 1 => self::STATUS_ACTIVE,
                                               2 => self::STATUS_INACTIVE,
                                               3 => self::STATUS_CANCELLED
                                             );

    public function getTypeName() {
        return self::$projectTypes[$this->get_type()];
    } 

}

These constants can be accessed using

self::STATUS_ACTIVE

from within the class, or

Project::STATUS_ACTIVE

from outside;

and the array can be accessed using

self::$project_types

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜