簡介
# Lowercase command name
package Mojolicious::Command::mycommand;
use Mojo::Base 'Mojolicious::Command';
# Short description
has description => 'My first Mojo command';
# Usage message from SYNOPSIS
has usage => sub { shift->extract_usage };
sub run {
my ($self, @args) = @_;
# Magic here! :)
}
1;
=head1 SYNOPSIS
Usage: APPLICATION mycommand [OPTIONS]
Options:
-s, --something Does something
=cut
Mojolicious::Command 是Mojolicious中所有命令的抽象基類。
屬性
app
my $app = $command->app;
$command = $command->app(Mojolicious->new);
當前對象所屬的應用程序,默認為Mojo::HelloWorld對象。
# Introspect
say "Template path: $_" for @{$command->app->renderer->paths};
description
my $description = $command->description;
$command = $command->description('Foo');
當前命令對象的簡短描述,用于命令列表。
quiet
my $bool = $command->quiet;
$command = $command->quiet($bool);
盡量少的輸出命令信息。
usage
my $usage = $command->usage;
$command = $command->usage('Foo');
命令的使用信息,用于顯示幫助信息。
方法
Mojolicious :: Command繼承Mojo :: Base中的所有方法,并實現以下方法。
chmod_file
$command = $command->chmod_file('/home/sri/foo.txt', 0644);
更改文件的訪問權限。
chmod_rel_file
$command = $command->chmod_rel_file('foo/foo.txt', 0644);
更改相對于當前工作目錄的文件的訪問權限。
create_dir
$command = $command->create_dir('/home/sri/foo/bar');
創建一個目錄。
create_rel_dir
$command = $command->create_rel_dir('foo/bar/baz');
創建一個相對于當前目錄的目錄。
extract_usage
my $usage = $command->extract_usage;
使用Mojo::Util中的extract_usage方法提取當前文件中摘要信息(SYNOPSIS)。
help
$command->help;
輸出當前命令的 usage 信息。
rel_file
my $path = $command->rel_file('foo/bar.txt');
返回相對于當前工作目錄的Mojo::File對象。
render_data
my $data = $command->render_data('foo_bar');
my $data = $command->render_data('foo_bar', @args);
使用Mojo::Loader和Mojo::Template類對命令類DATA段中模板進行渲染。
render_to_file
$command = $command->render_to_file('foo_bar', '/home/sri/foo.txt');
$command = $command->render_to_file('foo_bar', '/home/sri/foo.txt', @args);
使用Mojo::Loader和Mojo::Template類對命令類DATA段中模板進行渲染。并且渲染得到的內容寫到文件中,并在必要的時候創建目錄。
render_to_rel_file
$command = $command->render_to_rel_file('foo_bar', 'foo/bar.txt');
$command = $command->render_to_rel_file('foo_bar', 'foo/bar.txt', @args);
使用Mojo::Loader和Mojo::Template類對命令類DATA段中模板進行渲染。并且渲染得到的內容寫到相對于當前工作目錄的文件中,并在必要的時候創建目錄。
run
$command->run;
$command->run(@ARGV);
運行當前命令對象,需要在子類中重載。
write_file
$command = $command->write_file('/home/sri/foo.txt', 'Hello World!');
將文件寫入文件中,并在必要時創建目錄。
write_rel_file
$command = $command->write_rel_file('foo/bar.txt', 'Hello World!');
將文件寫入相對于當前工作目錄的文件中,并在必要時創建目錄。