菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
2658
0

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

原创
05/13 14:22
阅读数 3121

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

发表评论

0/200
2658 点赞
0 评论
收藏
为你推荐 换一批