Subscribe to PHP Freaks RSS

Symfony Console Beyond the Basics – Helpers and Other Tools

syndicated from www.sitepoint.com on September 14, 2017

It's undeniable how useful console commands can be when developing software. Not too long ago we re-introduced the Symfony Console component.

This component allows us to create structured and testable CLI commands. We created some simple commands and tested them; but when our commands become bigger and more complex, we need a different set of tools.

This is what we are going to look at today: advanced Symfony console tools.

Let's create a command that we can use to show some of these features. Most of the basic functionality was shown in the re-introduction to the Symfony console article, so be sure to check it before advancing - it's a quick but useful read!

Console screenshot

Installation

composer require symfony/console

Essential information about Composer can be found here, and if you're not familiar with well designed isolated PHP environments in which to develop your PHP apps like Vagrant, we have a fantastic book explaining it all in depth available for purchase here.

Creating our command

Let's create a command for an all time favorite: Fizzbuzz.

Fizzbuzz is a simple problem often used in programming interviews to assert the programming competence of the interviewee. The definition of Fizzbuzz normally comes in the following form:

Write a program that prints the numbers from 1 to x. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

Our command will receive an argument which will be the top limit for Fizzbuzz.

First of all, let's create our Fizzbuzz class.

<?php 
declare(strict_types=1);

namespace FizzBuzz;

class Fizzbuzz{

public function isFizz(int $value): bool{ if($value % 3 === 0){ return true; } return false; }

public function isBuzz(int $value): bool{ if($value % 5 === 0){ return true; } return false; }

public function calculateFizzBuzz(int $number): bool{ if($this->isFizz($number) && $this->isBuzz($number)){ echo "FizzBuzz \n"; return true; } if($this->isFizz($number)){ echo "Fizz \n"; return true; } if($this->isBuzz($number)){ echo "Buzz \n"; return true; } echo $number . "\n"; return true; }

public function firstNFizzbuzz(int $maxValue): void{ $startValue = 1;

while($startValue <= $maxValue){ $this->calculateFizzBuzz($startValue); $startValue++; } } }

Pretty straightforward. The firstNFizzbuzz() method prints the results of Fizzbuzz for a $maxValue of numbers. It does this by calling the calculateFizzBuzz() method recursively.

Next, let's write our command. Create a FizzCommand.php file with the following contents:

Continue reading %Symfony Console Beyond the Basics – Helpers and Other Tools%