从控制器调用shell类

时间:2013-10-18 01:25:23

标签: shell cakephp controller cmd

我有一个converterShell类,我需要从控制器调用它。该命令将转换视频。当我从cmd测试时,它工作,但我需要在我的文件移动到上传文件夹后调用。我想把“调用”放在一个函数上,并在电影已经移动时调用。但问题是调用shell类。以下是代码:

    class ConverterShell extends AppShell {
    public function main() {
        shell_exec('cd webroot\files\ && ffmpeg -i ' .fonte. 'whatever.wmv ' .destino. 'BLABLABLA.mp4');
    }

aaaand

    public function arquivos() {
        $this->autoRender = false;

        $name = $this->request->params['form']['upload']['name'];
        $type = $this->request->params['form']['upload']['type'];
        $tmp_name = $this->request->params['form']['upload']['tmp_name'];
        $error = $this->request->params['form']['upload']['error'];
        $size = $this->request->params['form']['upload']['size'];

        $path_parts = pathinfo($name);
        $formato = ($path_parts['extension']);
        $nome = ($path_parts['filename']);          

        $tamanho = ((($size)/1024)/1024);
        $tamanho_mb = number_format($tamanho, 2, '.', '');
        $string = $name;

        echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
        if(!$error) {
            if(move_uploaded_file($tmp_name, WEBROOT_FOLDER . 'files/uploads/' . $name)) {
                $this->call function here();
                exit('OK!');
        } else {
            exit('Erro!');
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你应该忽略混合控制台和应用程序逻辑的想法,它们应该分开。相反,您可以简单地将转换器功能放在library class中,并在控制器和shell中使用它。

像这样(未经测试的CakePHP 2.x示例代码):

<强> /app/lib/Converter.php

class Converter {
    static public function convert($source, $destination) {
        $source = escapeshellarg(fonte . $source);
        $destination = escapeshellarg(destino . $destination);

        shell_exec('cd webroot\files\ && ffmpeg -i ' . $source . ' ' . $destination);
    }
}

<强> /app/Console/Command/ConverterShell.php

App::uses('Converter', 'Lib');

class ConverterShell extends AppShell {
    public function main() {
        Converter::convert('whatever.wmv', 'BLABLABLA.mp4');
    }
}

<强> /app/Controller/WhateverController.php

App::uses('Converter', 'Lib');

class WhateverController extends AppController {

    ...

    public function arquivos() {
        ...

        if(!$error) {
            if(move_uploaded_file($tmp_name, WEBROOT_FOLDER . 'files/uploads/' . $name)) {
                Converter::convert($name, $nome . '.mp4');
                exit('OK!');
            } else {
                exit('Erro!');
            }
        }
    }
}