How to add a Logo to Symfony Console Component
Currently I am creating a small console application for AceProject. (Github) I never worked with the Symfony CLI Component (CLI = Command Line Interface) but it works like a charm. You can create your own CLI applications in a breeze. And I already tried other php command line frameworks – most of the frameworks were complicated, complicated in the sense of understanding and creating simple CLI apps.
So what I wanted was to add a big ascii logo like the one in composer:
I could not simply print the logo in the constructor or on top of the script because the symfony component uses own “print” methods (write / writeln) and you can hide them with the –quiet option, you cant do this when you use your own print function.
So, the way to show own logo above the help screen is to create own Class which extends the Application Class. Then instead of creating an instance of Application I create an instance of my own class. My own class then has the definition for my own logo. At first, here is the old way (without the logo)
file: myapp.php
1 2 3 4 5 6 |
require __DIR__ . '/vendor/autoload.php'; $console = new Application('My cool app', '1.0'); //Register your commands $console->register(...); //run the script: $console->run(); |
And now with the logo:
At first we create a new class – lets name it myapp.php (you need to autoload it!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?php use Symfony\Component\Console\Application; class MyApp extends Application { private static $name = "MyApp"; /** * @var string */ private static $logo = <<<LOGO /\ _ __ ___ _ _ / \ _ __ _ __ | '_ ` _ \| | | | / /\ \ | '_ \| '_ \ | | | | | | |_| |/ ____ \| |_) | |_) | |_| |_| |_|\__, /_/ \_\ .__/| .__/ __/ | | | | | |___/ |_| |_| LOGO; /** * MyApp constructor. * * @param string $name * @param string $version */ public function __construct( $name = 'UNKNOWN', $version = 'UNKNOWN') { $this->setName(static::$name); $this->setVersion($version); parent::__construct($name, $version); } /** * @return string */ public function getHelp() { return static::$logo . parent::getHelp(); } } |
And now you simply change the second line from the first example. It should instanciate MyApp and not Application.
1 2 3 4 5 6 |
require __DIR__ . '/vendor/autoload.php'; $console = new MyApp('My cool app', '1.0'); //Register your commands $console->register(...); //run the script: $console->run(); |
That way you can not only add a custom ascii logo but you can also change the behaviour how your app initializes or shows the help message.
BTW: I use this page to create ASCII Logos. 🙂