asika/php-code-generator

该包已被废弃且不再维护。作者建议使用 asika/muse 包。

PHP 代码生成器。她是女神,她是创造者。

安装: 274

依赖: 0

推荐者: 0

安全: 0

星标: 24

关注者: 2

分支: 2

开放问题: 1

类型:php-code-generator

2.0.0 2014-12-22 02:14 UTC

This package is auto-updated.

Last update: 2022-02-01 12:30:56 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

仓库已弃用,请参阅: Muse

通过 Composer 安装

在您的 composer.json 中添加此依赖项。

{
    "require": {
        "asika/php-code-generator": "2.*",
        "windwalker/console": "~2.0"
    }
}

或者创建一个项目

php composer.phar create-project asika/php-code-generator php-code-generator 2.*

入门指南

PHP 代码生成器是一个基于命令行的程序,我们将通过 CLI 执行所有操作。请输入

php bin/generator

您将获得此帮助信息

PHP Code Generator - version: 2
------------------------------------------------------------

[generator Help]

The default application command

Usage:
  generator <command> [option]


Options:

  -h | --help       Display this help message.
  -q | --quiet      Do not output any message.
  -v | --verbose    Increase the verbosity of messages.
  --ansi            Set 'off' to suppress ANSI colors on unsupported terminals.
  -p | --path       Dest path.
  -t | --tmpl       Sub template name.

Commands:

  gen             Genarate operation.
  tmpl-init       Init a new template.
  tmpl-convert    Convert a directory and files back to a template.

通过 Acme 模板生成代码

Acme 模板是 PHP 代码生成器中的默认模板,生成代码非常简单,请输入

php bin/generator gen acme test/MyApp

现在您将看到如下信息

$ php bin/generator gen acme test/MyApp
File created: /var/www/php-code-generator/test/MyApp/admin/article/edit.twig
File created: /var/www/php-code-generator/test/MyApp/admin/article/index.twig
File created: /var/www/php-code-generator/test/MyApp/admin/category/edit.twig
File created: /var/www/php-code-generator/test/MyApp/admin/category/index.twig
File created: /var/www/php-code-generator/test/MyApp/article.twig
File created: /var/www/php-code-generator/test/MyApp/global/index.html
File created: /var/www/php-code-generator/test/MyApp/index.html
File created: /var/www/php-code-generator/test/MyApp/index.twig

将您的子模板放入 Acme 模板

现在您可以将代码放入 src/AcmeTemplate/Template/mytmpl

然后使用此命令生成您的子模板

php bin/generator gen acme test/MyApp2 -t mytmpl

创建您的项目模板

现在一切都很简单,但如何创建我们自己的模板呢?我们必须编写一些代码来配置路径和变量。

初始化一个示例模板

使用此命令初始化新模板。

php bin/generator tmpl-init flower
File created: /var/www/php-code-generator/src/FlowerTemplate/Action/ConvertAction.php
File created: /var/www/php-code-generator/src/FlowerTemplate/Action/CopyAllAction.php
File created: /var/www/php-code-generator/src/FlowerTemplate/Task/Convert.php
File created: /var/www/php-code-generator/src/FlowerTemplate/Task/Generate.php
File created: /var/www/php-code-generator/src/FlowerTemplate/Template/default/DefaultClass.php
File created: /var/www/php-code-generator/src/FlowerTemplate/FlowerTemplate.php

好的,我们创建了一个名为 flower 的示例模板,该模板位于 src/FlowerTemplate,入口类为 FlowerTemplate。实际上您可以手动创建它,但这会稍微复杂一些,所以我们最好先使用示例。

配置变量和路径

打开 FlowerTemplate,您可以在此设置替换字符串和复制路径

注册替换变量

protected $tagVariable = array('{@', '@}');

protected function registerReplaces($io, $replace = array())
{
    $item = $io->getOption('n', 'sakura');

    /*
     * Replace with your code name.
     */

    // Set item name, default is sakura
    $replace['item.lower'] = strtolower($item);
    $replace['item.upper'] = strtoupper($item);
    $replace['item.cap']   = ucfirst($item);

    // Set project name
    $replace['project.class'] = 'CodeGenerator';

    return $replace;
}

此示例表示我们可以键入 -n {item} 来定义变量名称。在模板代码中,{@item.lower@} /{@item.upper@} /{@item.cap@} 将替换为项目名称。

sakura 是未提供 -n 参数时的默认值。这是一个示例,如果未找到 -n,则退出并提示用户输入此参数。

$item = $io->getOption('n') ? : exit('Please give me item using "-n {item_name}"');

您可以将多个字符串添加到 $replace 数组中,请记住您将需要每个小写、大写和首字母大写的,并且不要忘记返回它。

注册配置和路径

protected function registerConfig($io, $config)
{
    /*
     * Replace with your project path.
     */

    $subTemplate = $io->getOption('t', 'default');
    $dest        = $io->getArgument(1) ? : 'generated';

    $config['path.src']  = __DIR__ . '/Template/' . $subTemplate;
    $config['path.dest'] = GENERATOR_PATH . '/' . $dest;

    return $config;
}

您可以在此方法中设置一些有用的配置,最重要的是 path.srcpath.dest。这两个配置告诉 PHP 代码生成器代码从哪里来以及代码复制到哪里。

GENERATOR_PATH是PHP代码生成器的根路径,而$io->getArgument(1)表示获取你命令的第二个参数(第一个是0)。

任务 & 操作

我们有两个默认的任务控制器,分别是GenerateConvert

Generate任务执行代码生成操作,Convert任务可以帮助我们将代码转换回模板。在任务控制器中,我们可以使用doAction()执行不同的操作来完成我们想要做的事情。

Generate控制器类

namespace FlowerTemplate\Task;

use FlowerTemplate\Action;
use CodeGenerator\Controller\AbstractTaskController;

class Generate extends AbstractTaskController
{
	public function execute()
	{
		$this->doAction(new Action\CopyAllAction);
	}
}

CopyAllAction

namespace FlowerTemplate\Action;

use CodeGenerator\Action\AbstractAction;
use CodeGenerator\FileOperator\CopyOperator;

class CopyAllAction extends AbstractAction
{
	protected function doExecute()
	{
		$copyOperator = new CopyOperator($this->io, (array) $this->config['tag.variable']);

		$copyOperator->copy($this->config['path.src'], $this->config['path.dest'], $this->config['replace']);
	}
}

这两个类都非常简单,遵循单一职责原则。我们可以在一个控制器中组织多个操作,如下所示:

class Generate extends AbstractTaskController
{
	public function execute()
	{
		$this->doAction(new Action\CopyAllAction);

		$this->doAction(new Action\ImportSqlAction);

		$this->doAction(new Action\Github\CloneSomeRepoAction);

		$this->doAction(new Action\User\CreateNewUserAction);
	}
}

单一操作类的优点是我们可以将每个类在不同的任务中重复使用。

文件操作

操作类

目前我们提供了两个操作类,copyOperator帮助我们复制代码并替换标签到变量中,convertOperator也帮助我们复制代码,但是用标签替换变量。

只需创建一个实例并使用复制方法

$copyOperator = new CopyOperator($this->io, array('{@', '@}'));

$copyOperator->copy($src, $dest, $replaceArray);

未来还将有更多的操作类(例如:databaseOperatorgitOperator)。

文件系统

有三个文件系统类:PathFileFolder,它们继承自Windwalker Filesystem包,请参阅:https://github.com/ventoviro/windwalker-filesystem

简单用法

namespace CodeGenerator\Filesystem;

Filesystem\Folder::copy($src, $dest);
Filesystem\Folder::move($src, $dest);
Filesystem\Folder::create($path);
Filesystem\Folder::delete($path);

Filesystem\File::copy($src, $dest);
Filesystem\File::move($src, $dest);
Filesystem\File::write($path, $buffer);
Filesystem\File::delete($path);

// Replace / and \ to DIRECTORY_SEPARATOR
$path = Filesystem\Path::clean($path);

因此,您可以在Action类中使用文件系统类来帮助您操作文件和目录。

创建新的任务

如果您想创建一个新的任务控制器,这将需要一些步骤来创建任务。这个过程并不容易,我们将在未来使这个过程更简单。

(1) 创建新的命令

src/CodeGenerator/Windwalker/Command/MyTask/MyTask.php中创建一个命令类

namespace CodeGenerator\Windwalker\Command\MyTask;

use CodeGenerator\Controller\GeneratorController;
use CodeGenerator\Windwalker\IO;
use Windwalker\Console\Command\Command;

class MyTask extends Command
{
	protected $name = 'mytask';

	protected $description = 'Desc of my task.';

	protected $usage = 'mytask <cmd><tmpl-name></cmd> <option>[option]</option>';

	public function configure()
	{
		parent::configure();
	}

	protected function doExecute()
	{
		$controller = new GeneratorController(new IO($this));

		$controller->setTask('mytask')->execute();
	}
}

如何使用Windwalker Console和命令?请参阅:https://github.com/ventoviro/windwalker-console

(2) 将您的命令注册到应用程序中

src/CodeGenerator/Windwalker/Application::registerCommands()中注册此命令

protected function registerCommands()
{
    $this->addCommand(new Command\Generate\Generate);
    $this->addCommand(new Command\Init\Init);
    $this->addCommand(new Command\Convert\Convert);

    // Add here
    $this->addCommand(new Command\MyTask\Task);
}

您将得到如下所示的新帮助

Available commands:

  gen             Genarate operation.
  tmpl-init       Init a new extension.
  tmpl-convert    Convert a code folder back to a template.
  mytask          Desc of my task.

(3) 创建新的任务控制器

src/FlowerTemplate/Task/MyTask.php中创建一个类

namespace FlowerTemplate\Task;

use FlowerTemplate\Action;
use CodeGenerator\Controller\TaskController;

class MyTask extends TaskController
{
	public function execute()
	{
		$this->doAction(new Action\CopyAllAction);
	}
}

现在您可以在这里执行一些操作。

(4) 测试您的任务

键入此命令并进入您的任务控制器

php bin/generator mytask <arguments>

集成到您的项目或框架

PHP代码生成器可以集成到任何框架,而不是默认的Windwalker Console应用程序。只需创建一个IO类来帮助PHP代码生成器输入和输出一些信息

use CodeGenerator\IO\IOInterface;

class MyIOAdapter implements IOInterface
{
    // Implelemt this interface
}

然后在您的项目入口处使用GeneratorController(例如:Symfony Console)

$controller = new GeneratorController(new MyIOAdapter($input, $output));

$controller->setTask($input->getArgument('task'))->execute();

非常好,祝您在代码食谱中过得愉快。

待办

  • 数据库操作员
  • Git操作员
  • FTP操作员
  • 单元测试
  • 完成文档块
  • 易于添加任务控制器和命令