roolith / generator

使用 php 生成 php 文件

1.0.3 2021-09-29 10:05 UTC

This package is auto-updated.

Last update: 2024-08-29 05:19:04 UTC


README

使用 php 生成 php 文件

安装

composer require roolith/generator

使用方法

通过 composer 安装生成器后,创建一个名为 index.php 的文件,并添加以下代码 -

<?php
use Roolith\Generator\GeneratorFactory;

require_once __DIR__ . '/PATH_TO_YOUR_VENDOR/vendor/autoload.php';

$generator = GeneratorFactory::getInstance();
$generator
    ->setTemplateDirectory(__DIR__.'/template') // this is your template directory
    ->setProjectBaseDirectory(__DIR__) // this is project base directory
    ->watch($argv); // this $argv to get console arguments

现在在项目根目录下创建一个名为 template 的文件夹,并在 template 文件夹内创建一个名为 controller.txt 的文件,并添加以下代码 -

# outputBaseDir: Controllers
<?php
namespace Something;

class {{name}} extends Controller
{
    public function index()
    {
    }

    public function create()
    {
    }
}

outputBaseDir 表示 - 文件将在哪个文件夹中生成。{{name}} 表示命令名称参数。

现在运行以下命令

php index.php generate controller DemoController

它应该在 Controllers 文件夹中创建一个 DemoController.php 文件。如果您想添加另一个模板,请添加 test.txt 并添加您的模板代码,然后运行以下命令 -

php index.php generate test something

添加自定义命令

php index.php test

要使其工作,创建一个 TestCommand.php 类,其外观如下 -

<?php
use Roolith\Generator\Command;
use Roolith\Generator\Console;
use Roolith\Generator\FileGenerator;
use Roolith\Generator\FileParser;
use Roolith\Generator\Interfaces\CommandInterface;

class TestCommand implements CommandInterface
{
    public function register()
    {
        return [
            'name' => 'test',
            'alias' => [],
            'typeAlias' => [],
        ];
    }

    public function handle(Command $command, Console $console, FileParser $fileParser, FileGenerator $fileGenerator)
    {
        $console->output('Test command registered!');
    }
}

然后通过生成器类注册您的命令 -

$generator
    ->setTemplateDirectory(__DIR__.'/template')
    ->setProjectBaseDirectory(__DIR__)
    ->registerCommandClass([
        TestCommand::class
    ])
    ->watch($argv);

已添加一个 demo 文件夹,其中包含更多详细信息。

测试用例

$ ./vendor/bin/phpunit --testdox tests
PHPUnit 9.2.6 by Sebastian Bergmann and contributors.

Command
 ✔ Should get argument name
 ✔ Should get argument type
 ✔ Should get argument value
 ✔ Should get argument type with alias
 ✔ Should get registered command by name

Console
 ✔ Should set arguments
 ✔ Should remove first item from argument
 ✔ Should return bool for has arguments

File Generator
 ✔ Should set file extension
 ✔ Should set project directory
 ✔ Should save file

File Parser
 ✔ Should add default instructions
 ✔ Should set file extension
 ✔ Should set directory
 ✔ Should check whether template exists or not
 ✔ Should parse template

Generate Factory
 ✔ Should have get instance method

Generator
 ✔ Should create instance
 ✔ Should set template directory
 ✔ Should set project base directory
 ✔ Should have watch method
 ✔ Should register custom command

Time: 00:00.012, Memory: 6.00 MB

OK (22 tests, 28 assertions)