HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Printing to terminal in a color

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
printingterminalcolor

Problem

Basically, I wish to have 3 printers to print in error state, success state or info state which means nothing but different colors.

class ColorCode{
        private static $options = [
            "dark_gray"     => "1;30",
            "light_gray"    => "0;37",
            "blue"          => "0;34",
            "green"         => "0;32",
            "cyan"          => "0;36",
            "red"           => "0;31",
            "yellow"        => "1;33"
        ];

        public static function get($key){
            if(isset(self::$options[$key])){
                return self::$options[$key];
            } else {
                return '';
            }
        }
    }

    class ColorPrint {
        public $color = '';

        function __construct($color) {
            $this->color = ColorCode::get($color);
        }

        public function printc($msg) {
            echo "\033[". $this->color ."m".$msg."\033[0m\n";
        }

    }

    $out = [
        'error'     => new ColorPrint('red'),
        'info'      => new ColorPrint('cyan'),
        'success'   => new ColorPrint('green'),
    ];
    $out['error']->printc('Invalid Option');

Solution

I like your code, but I just have a couple of small points:

  • Be consistent with your spacing (around { and especially .).



  • I doubt that this will work on Windows, so I would check if the script is run on Windows, if it is, just print without color (or find a way to use color in Windows), and maybe trigger a warning.



  • I would rename printc, either to the shorter print (because it's easier to remember, and you don't really lose any meaning), to print_color (if you want to make it really really explicit that it is in color), or print_console (in case you also later implement something like print_web with CSS).



  • I would not just ignore it if a color is requested that does not exist, but handle it in some way (throw an exception, trigger a warning, etc). Otherwise users might wonder why ligth_gray or orange do not result in any color changes.

Context

StackExchange Code Review Q#77490, answer score: 4

Revisions (0)

No revisions yet.