Lets build a utopian cli clone

in #utopian-io7 years ago (edited)

What Will I Learn?

In this tutorial, you will learn to build a useful real world php command line app. It is the 2nd in a series of Building command line apps in php

Requirements

To follow along, you must have gone through my first tutorial in this series (https://utopian.io/utopian-io/@therealsmat/building-command-line-applications-in-php). It contains details on how to get up and running with building command line apps in php.

Difficulty

Intermediate

Tutorial Contents

We are going to build a clone of @amosbastian's Command Line Tool in php.

Step 1

Create a new folder for this project and navigate into the folder. On your terminal (or command line for windows), type

$ sudo mkdir utopian-cli && cd utopian-cli

Step 2

Create a composer.json file and add the following lines

{
    "require": {
        "symfony/console": "~2.0"
    }
}

On your terminal, run composer install. This will pull in the console package for our use.

Step 3

Create a file named utopian. Note that this file has no extention. Open the file and add this code at the top.

#! /usr/bin/env php.

Also require composer autoload like this require 'vendor/autoload.php';. You should have this now;

#! /usr/bin/env php

<?php

require 'vendor/autoload.php';

Step 4
Now lets setup out tool.

<?php

use Symfony\Component\Console\Application;

require 'vendor/autoload.php';

$app = new Application("PHP Console tool for utopian.io", "1.0");

$app->run();

Step 5

Our first command: Moderators

  • Create a directory called src. In src, create a file named ModeratorsCommand.php. This will contain the logic for our Moderators command.
  • In the ModeratorsCommand.php file, paste the following code.
<?php 

namespace therealsmat;

use Symfony\Component\Console\Command\Command;

class ModeratorsCommand extends command {
            
            public function configure(){

            }

            public function execute(){

            }
}

Add the following to your composer.json file.

,
    "autoload": {
        "psr-4": {
            "therealsmat\\": "src"
        }
    }

This will enable us map therealsmat namespace to our src directory. Of course you are free to change therealsmat to anything you want.

Next run composer dump-autoload from your terminal.

Step 6
Lets think for a moment. What do we want to do exactly? We need to make http calls to utopian api. Of course, there are several ways to do this. We'll be using the popular guzzle-http client for that.
In your composer.json file, add the require "guzzlehttp/guzzle": "~6.0".

Go to your command line and run composer update to pull in the client.

Add a protected property protected $baseUrl = 'https://api.utopian.io/api'; to the command class.

Now lets create a helper method in our command class to make http calls easier. We'll use the popular http verbs as the method names. So for a GET request,

protected function get($url)
    {
        $uri = $this->baseUrl.$url;
        $response = (new Client)->get($uri)->getBody();
        return (string) $response;
    }

Now lets get the number of moderators we have on utopian.

private function countModerators(OutputInterface $output){
        $moderators = json_decode($this->get('/moderators'), true);
        $output->writeln($moderators['total']);
    }

You entire class should look like this now;

<?php

namespace therealsmat;

use GuzzleHttp\Client;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ModeratorsCommand extends command{

    protected $baseUrl = 'https://api.utopian.io/api';

    public function configure()
    {
        $this->setName('moderators')
            ->setDescription("List Moderators and their activities")
            ->addOption('count',null,InputOption::VALUE_OPTIONAL, 'Count the number of moderators on utopian', 1);
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        if ($input->getOption('count')) {
            return $this->getModerators($output);
        } 
    }

    private function countModerators(OutputInterface $output){
        $moderators = json_decode($this->get('/moderators'), true);
        $output->writeln($moderators['total']);
    }

    private function get($url)
     {
        $uri = $this->baseUrl.$url;
        $response = (new Client)->get($uri)->getBody();
        return (string) $response;
    }

Finally, we have to register this new command in our executable. Our utopian file should now look like this;

#! /usr/bin/env php

<?php

use therealsmat\ModeratorsCommand;
use Symfony\Component\Console\Application;

require 'vendor/autoload.php';

$app = new Application("PHP Console tool for utopian.io", "1.0");
$app->add(new ModeratorsCommand);
$app->run();

Go to your command line, then run ./utopian moderators --count,
utopian-moderators.gif

You should be up and running with building command line apps.

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

this is the good tutorial

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @therealsmat I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

This is an exceptional tutorial

Coin Marketplace

STEEM 0.27
TRX 0.21
JST 0.039
BTC 97426.90
ETH 3593.28
USDT 1.00
SBD 3.88