ThinkPHP5 使用 Laravel 的创建软链接命令 storage:link


V5.1.24+版本开始,你可以通过命令行指令快速生成一条指令,包括指令类文件

1.创建一个自定义命令类文件

php think make:command StorageLinkCommand storage:link

2.配置 application/command.php 文件

return [
   'storage:link'	=>	'app\command\StorageLinkCommand',
];

3.新增自定义函数

if (! function_exists('base_path')) {
    /**
     * Get the path to the base folder.
     *
     * @param  string  $path
     * @return string
     */
    function base_path($path = '')
    {
        return env('root_path').($path ? ltrim($path, DIRECTORY_SEPARATOR) : ltrim($path, DIRECTORY_SEPARATOR));
    }
}

if (! function_exists('public_path')) {
    /**
     * Get the path to the public folder.
     *
     * @param  string  $path
     * @return string
     */
    function public_path($path = '')
    {
        return base_path('public').($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

if (! function_exists('windows_os')) {
    /**
     * Determine whether the current environment is Windows based.
     *
     * @return bool
     */
    function windows_os()
    {
        return strtolower(substr(PHP_OS, 0, 3)) === 'win';
    }
}

if (! function_exists('storage_path')) {
    /**
     * Get the path to the storage folder.
     *
     * @param  string  $path
     * @return string
     */
    function storage_path($path = '')
    {
        return base_path().'storage'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }
}

以上函数均参考自 Laravel ,提取了需要用到的部分

4.编写命令相关代码

打开步骤 1 生成的自定义命令类文件 application/command/StorageLinkCommand.php 将以下代码复制进去:

protected function configure()
{
	// 指令配置
	$this->setName('storage:link')
	// 设置参数
	->setDescription('Create a symbolic link from "public/storage" to "storage/app/public"');
}

protected function execute(Input $input, Output $output)
{

	if (file_exists(public_path('storage'))) {
		return $this->error('The "public/storage" directory already exists.');
	}

	$this->link(
		storage_path('app/public'), public_path('storage')
	);
	// 指令输出
	$output->writeln('The [public/storage] directory has been linked.');
}

public function link($target, $link)
{
	if (! windows_os()) {
		return symlink($target, $link);
	}

	$mode = $this->isDirectory($target) ? 'J' : 'H';
	exec("mklink /{$mode} ".escapeshellarg($link).' '.escapeshellarg($target));
}

public function isDirectory($directory)
{
	return is_dir($directory);
}

以上代码同样参考 Laravel ,提取了需要用到的部分

5.创建命令需要的目录

根目录下创建 storage/app/public 目录

6.运行命令

项目根目录下打开命令行,输入 php think storage:link 即可使用创建软链接的命令