How to create a custom CLI and use it in Symfony (part1)

TECHNO CRAFT
3 min readNov 17, 2021

--

Sometimes you have special needs, which Symfony or its community has not yet developed.

For example a code that is repeated often in your projects, and that you want to generate it with your own command line,

To automate these recurring tasks, Symfony Console Command is the ideal component,

On the other hand, you are a developer who loves open source and wants to share your work with others, and you are absolutely right to think and do so ;-)

In this article I will detail step by step to create a bundle that executes a command and this one returns an answer according to the need.

We will also see how to share it on packagist, and to reuse it in any symfony project with a touch of composer require coffeeshop/maker-coffee-bundle.

To make this happen, I thought of a revolutionary idea, when i codding I am too lazy to make a coffee for my self, so I had the idea of ​​creating a command that makes me a coffee and I can continue to working without going to the cafeteria.

Hmmmmmmmm … I think I‘ll file a patent.

Lets get started…the structure of this article is :

Part 1

1- file and folder structure

2- creation of this structure

3- mandatory files for the bundle

Part 2

4- creation of the command :-D

5- push it in the packagist

6- installed it in a Symfony project and run the command

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

1- file and folder structure

  • maker-coffee-bundle/ (main folder)
  • — bin/ (folder)
  • — bin/console (file)
  • — src/ (folder)
  • — — src/MakeMeCoffeeBundle.php (php file)
  • — — src/Command (folder)
  • — — src/Command/CoffeCommand.php (php file)
  • — vendor (folder)
  • — .gitignore (git file)
  • — composer;json (json file)
  • — composer.lock (json file)

2- creation of this structure

  • create folder with named maker-coffee-bundle go in it
  • - run `composer init` and feel the questions

this command will create

  • src/
  • - vendor/
  • - composer.json

To make a namespace as bundle in composer.json file change ligne 7

from :

“Coffeeshop\\MakerCoffeeBundle\\”: “src/”

to :

“CoffeeShop\\Bundle\\MakerCoffeeBundle\\”: “src/”

See mendatory rules in symfony

3- mandatory files for the bundle

lets add what is missing…

create empty files in their own forlder, empty for the moment:

  • ./bin/console
  • ./src/MakeMeCoffeeBundle.php
  • ./src/Command/CoffeeCommand.php

see image below=>

/!\ take care of names of all of them /!\

/!\ and i know you are a greate dev and you did not forget git init ;-) /!\

put in .gitignore :

  • /vendor/
  • /bin/

yes /bin/… also because you will need it only for test, and when you will use this bundle in a Symfony project, Symfony will load your command in the porject.

To be continued… Part 2

--

--