自定义 make 脚本扩展 artisan make 命令

有时候,我们想自定义生成 php 类文件,于是自己写了一个,能兼容去调用 artisan make 命令。文件名就叫 make  放在与 artisan 相同目录下,

命令: php make --help

代码如下:

#!/usr/bin/env php
<?php
if($argv[1] == '--help' || empty($argv[1])){
    echo 'php make <type> [<path>] <filename>' . PHP_EOL . PHP_EOL;
    echo 'php make test demo  ==> tests/DemoTest.php' . PHP_EOL . PHP_EOL;
    echo 'php make service demoService ==> app/Services/DemoService.php' . PHP_EOL . PHP_EOL;
    echo 'php make class app/Mail orderShipped ==> app/Mail/OrderShipped.php' . PHP_EOL . PHP_EOL;
    echo 'php make model User ==> php artisan make:model User' . PHP_EOL . PHP_EOL;
    exit(0);
}

function stop($value){
    var_dump($value);
    exit;
}


$content['test'] = <<<'hdoc'
<?php
namespace Tests;
<<<'doc'

doc;
class {name} extends TestCase 
{

    public function content()
    {
        
    }
    
    public function test()
    {
        
    }
    
}
hdoc;


$content['service'] = <<<'hdoc'
<?php
namespace App\Services;

class {name}  
{
    public function __construct()
    {
        
    }

}
hdoc;


$content['class'] = <<<'hdoc'
<?php
namespace {namespace};

class {name}  
{
    public function __construct()
    {
        
    }

}
hdoc;


if(key_exists($argv[1], $content)){

    $content = $content[$argv[1]];
    $name = ucfirst($argv[2]);
    $path = '';
    switch($argv[1]){

        case 'test' :
            $name .= 'Test';
            $path = 'tests';
            break;
        case 'service':
            $path = 'app/Services';
            break;
        case 'class':
            $name = $argv[3];
            $path = rtrim($argv[2], '/');
            $content = str_replace('{namespace}', ucfirst(str_replace('/', '\\', $path)), $content);
            break;
    }

    if(!is_dir($path)) {
        mkdir($path, 0777, true);
    }

    $file = "$path/$name.php";
    file_put_contents($file, str_replace('{name}', $name, $content));
    echo 'create: ' . $file . PHP_EOL;

}else{

    $cmd = $argv[1];
    $argv = implode(' ', array_slice($argv,2));
    echo `php artisan make:$cmd $argv`;

}

 

posted @ 2023-06-29 14:23  心随所遇  阅读(16)  评论(0编辑  收藏  举报