将一个功能一分为二

时间:2019-03-01 01:56:44

标签: php laravel-4

出于可重用性,我计划将我的功能分为两个功能。基本上,该功能的概念是加载输入文件然后预览数据。

工作代码

public function uploadImportCsv()
    {
        $file = Input::file('file');
        $extension = $file->getClientOriginalExtension();
        $filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
        //upload to s3
        #doing upload to s3

        $data = [
            'title'=>[],
            'value'=>[]
            ];
    $results = Excel::load(Input::file('file'), function($reader){

            })->get();
    foreach ($results as $result) {
        foreach ($result as $key => $value) {
            if(!in_array($key, $data['title'])){
                array_push($data['title'], $key);
            }       
        }
        array_push($data['value'], $result);
    }

        return Response::json(['filename' => $filename, 'data' => $data]);
    }

分割后

public function previewCsv()
    {
        //Preview table
        $data = [
                'title'=>[],
                'value'=>[]
                ];
        $results = Excel::load(Input::file('file'), function($reader){

                })->get();
        foreach ($results as $result) {
            foreach ($result as $key => $value) {
                if(!in_array($key, $data['title'])){
                    array_push($data['title'], $key);
                }       
            }
            array_push($data['value'], $result);
        }
        return Response::json(['data' => $data]);
    }

    public function uploadImportCsv()
    {
        $file = Input::file('file');
        $extension = $file->getClientOriginalExtension();
        $filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
        //upload to s3
        #doing upload to s3

        $data = $this->previewCsv();


        return Response::json(['filename' => $filename,'data' => $data]);
    }

我从预览功能中调用了该功能,但是它不起作用。

1 个答案:

答案 0 :(得分:0)

如果您需要相同的结果,则不必从PreviewCsv函数返回json对象。

public function previewCsv()
{
    ....
    return $data;
}