Easysoole framework access to hyperfcommand

Time:2019-12-3

Warehouse address

Try easysoole custom commands

create a file

<?php

declare(strict_types=1);

namespace App\Command;

use EasySwoole\EasySwoole\Command\CommandInterface;

class DemoCommand implements CommandInterface
{
    public function commandName(): string
    {
        return 'demo:command';
    }

    public function exec(array $args): ?string
    {
        var_dump('Hello World');

        return 'success';
    }

    public function help(array $args): ?string
    {
        return 'help';
    }
}

Function

$ php easyswoole
  ______                          _____                              _
 |  ____|                        / ____|                            | |
 | |__      __ _   ___   _   _  | (___   __      __   ___     ___   | |   ___
 |  __|    / _` | / __| | | | |  \___ \  \ \ /\ / /  / _ \   / _ \  | |  / _ \
 | |____  | (_| | \__ \ | |_| |  ____) |  \ V  V /  | (_) | | (_) | | | |  __/
 |______|  \__,_| |___/  \__, | |_____/    \_/\_/    \___/   \___/  |_|  \___|
                          __/ |
                         |___/
Welcome To EASYSWOOLE Command Console!
Usage: php easyswoole [command] [arg]
Get help : php easyswoole help [command]
Current Register Command:
demo:command
help
install
start
stop
reload
phpunit

$ php easyswoole demo:command
string(11) "Hello World"
success

I have to say, it is quite simple.

Reform

Next, let’s transform some of the code and plug in the command of hyperf to easysoole.

Easysoole is very simple, all commands are saved inCommandContainerSo we can modify the entry file, find out all the commands in it, and dynamically translate them intoHyperfCommand, and then run it directlyHyperfCommandJust fine.

In order not toeasyswooleCommand line conflict, let’s create a new onehyperfOkay.

First we create a component

$ composer create hyperf/component-creater hyperf
Installing hyperf/component-creater (v1.1.1)
  - Installing hyperf/component-creater (v1.1.1): Downloading (100%)
Created project in hyperf
> Installer\Script::install
Setting up optional packages
What is your component name (hyperf/demo): hyperf-cloud/easyswoole-command
What is your component license (MIT) :
What is your component description : HyperfCommand for EasySwoole
What is your namespace (HyperfCloud\EasyswooleCommand):
Removing installer development dependencies

  Do you want to use hyperf/framework component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n):

  Do you want to use hyperf/di component ?
  [1] yes
  [n] None of the above
  Make your selection or type a composer package name and version (n):

...

And add components"hyperf/command": "1.1.*"Dependence.

Modify the root directory belowcomposer.json

{
    "require": {
        "easyswoole/easyswoole": "3.x",
        "hyperf-cloud/easyswoole-command": "dev-master"
    },
    "require-dev": {
        "swoft/swoole-ide-helper": "^4.2",
        "friendsofphp/php-cs-fixer": "^2.14",
        "mockery/mockery": "^1.0",
        "phpstan/phpstan": "^0.11.2"
    },
    "autoload": {
        "psr-4": {
            "App\\": "App/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "scripts": {
        "test": "co-phpunit -c phpunit.xml --colors=always",
        "cs-fix": "php-cs-fixer fix $1",
        "analyse": "phpstan analyse --memory-limit 300M -l 0 -c phpstan.neon ./App"
    },
    "repositories": {
        "hyperf": {
            "type": "path",
            "url": "./hyperf"
        },
        "packagist": {
            "type": "composer",
            "url": "https://mirrors.aliyun.com/composer"
        }
    }
}

Take over commandinterface

Let’s create aEasySwooleCommandTo take over everythingCommandInterface

<?php

declare(strict_types=1);

namespace HyperfCloud\EasyswooleCommand;

use EasySwoole\EasySwoole\Command\CommandInterface;
use EasySwoole\EasySwoole\Core;
use Hyperf\Command\Command;
use Symfony\Component\Console\Input\InputOption;

class EasySwooleCommand extends Command
{
    /**
     * @var CommandInterface
     */
    protected $command;

    /**
     * @var bool
     */
    protected $coroutine = false;

    public function __construct(CommandInterface $command)
    {
        parent::__construct($command->commandName());
        $this->command = $command;
    }

    public function configure()
    {
        $this - > addoption ('args','a ', inputoption:: value \ is \ array | inputoption:: value \ optional,' easysoole input ', []);
    }

    public function handle()
    {
        $args = $this->input->getOption('args');

        if (in_array('produce', $args)) {
            Core::getInstance()->setIsDev(false);
        }
        Core::getInstance()->initialize();

        $result = $this->command->exec($args);

        $this->output->success($result);
    }
}

increaseApplicationInitialize allCommandContainerMediumCommand

<?php

declare(strict_types=1);

namespace HyperfCloud\EasyswooleCommand;

use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Command\CommandContainer;
use Hyperf\Command\Command;
use Hyperf\Contract\ApplicationInterface;
use Symfony\Component\Console\Application as SymfonyApplication;

class Application implements ApplicationInterface
{
    use Singleton;

    protected $commands;

    public function __construct()
    {
        $container = CommandContainer::getInstance();

        $list = $container->getCommandList();

        foreach ($list as $name) {
            $this->commands[] = new EasySwooleCommand($container->get($name));
        }
    }

    public function add(Command $command)
    {
        $this->commands[] = $command;
    }

    public function run()
    {
        $application = new SymfonyApplication();
        foreach ($this->commands as $command) {
            $application->add($command);
        }

        return $application->run();
    }
}

Final transformation entry function

<?php

declare(strict_types=1);

use EasySwoole\EasySwoole\Command\CommandRunner;
use HyperfCloud\EasyswooleCommand\Application;

defined('IN_PHAR') or define('IN_PHAR', boolval(\Phar::running(false)));
defined('RUNNING_ROOT') or define('RUNNING_ROOT', realpath(getcwd()));
defined('EASYSWOOLE_ROOT') or define('EASYSWOOLE_ROOT', IN_PHAR ? \Phar::running() : realpath(getcwd()));

$file = EASYSWOOLE_ROOT . '/vendor/autoload.php';
if (file_exists($file)) {
    require $file;
} else {
    die("include composer autoload.php fail\n");
}

//Initialize commandcontainer
CommandRunner::getInstance();

if (file_exists(EASYSWOOLE_ROOT . '/bootstrap.php')) {
    require_once EASYSWOOLE_ROOT . '/bootstrap.php';
}

Application::getInstance()->run();

Executive orderdemo:command

$ php hyperf.php demo:command
string(11) "Hello World"


 [OK] success

start-upServer

$ php hyperf.php start -a produce

Create hyperfcommand

Next, we create aHyperfCommandLook at the effect.

<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Command\Command;

class Demo2Command extends Command
{
    public function __construct()
    {
        parent::__construct('demo:command2');
    }

    public function handle()
    {
        var_dump('Hello Hyperf Command.');
    }
}

modifybootstrap.php

<?php

declare(strict_types=1);

use EasySwoole\EasySwoole\Command\CommandContainer;
use App\Command\{DemoCommand, Demo2Command};
use HyperfCloud\EasyswooleCommand\Application;

CommandContainer::getInstance()->set(new DemoCommand());
Application::getInstance()->add(new Demo2Command());

results of enforcement

$ php hyperf.php demo:command2
string(21) "Hello Hyperf Command."

Written in the end

Hyperf is a high-performance and flexible PHP cooperation framework based on swoole 4.4 +. It has built-in cooperation server and a large number of commonly used components. Compared with the traditional framework based on php-fpm, its performance is improved qualitatively. It provides super-high performance while maintaining extremely flexible scalability. The standard components are implemented based on PSR standard and based on strong dependency injection design, which ensures that Most components or classes are replaceable and reusable.

In addition to the common MySQL client and redis client of the collaboration version, the framework component library also provides you with eloquent ORM, websocket server and client, JSON RPC server and client, grpc server and client, Zipkin / Jaeger (opentracing) client, guzzle HTTP client, elasticsearch client, consult client, etcd client, am of the collaboration version QP component, Apollo configuration center, Alibaba cloud ACM application configuration management, etcd configuration center, current limiter based on token bucket algorithm, general connection pool, fuse, swagger document generation, swoole tracker, blade and Smarty view engine, snowflake global ID generator and other components save the trouble of implementing the corresponding version of the program.

Hyperf also provides psr-11-based dependency injection container, annotation, AOP aspect oriented programming, psr-15-based middleware, custom process, psr-14-based event manager, redis / rabbitmq message queue, automatic model cache, psr-16-based cache, crontab second level timed task, translation internationalization, validation validator and other very convenient functions , to meet the rich technical and business scenarios, out of the box.