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 即可使用创建软链接的命令,效果图:

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

7. 结语#

最近由于项目需要,正在使用 ThinkPHP5.1 开发,但是用习惯了 Laravel 后再用其他框架,总感觉不顺手,只好自己动手把 ThinkPHP 改成自己喜欢的形状了。

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

本作品采用《CC 协议》,转载必须注明作者和本文链接
www.haowuliaoa.com
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。