试图在cakephp中获得控制台脚本来访问控制器


trying to get a console script in cakephp to access a controller

所以,我一直试图在CAKEPHP中获得一个控制台脚本。但是它不允许我使用$uses成员访问控制器。

我已经尝试将一个数组分配给$uses,并将一个非数组分配给$uses,在我的JobManagerClass内部的方法外部和内部,没有任何工作。

现在,我有……

<?php

类JobManagerShell扩展AppShell {

public $uses;
public function main() {
    $this->_processJobs();
}
public function _processJobs() {
    $this->uses = array("Job");
    $jobs = $this->Job->find("all");
    foreach ($jobs as $job) {
        if ($job["is_running"] == 1) exit;
    }
    foreach ($jobs as $job) {
        $id = $this->Job->id = $job["id"];
        $this->Job->saveField(array("Job" => array("is_running" => 1)));
        exec($job["command"] . "2> errors.txt");
        $errorsFile = fopen("errors.txt");
        $errorsText = fread($errorsFile);
        fclose($errorsFile);
        $this->Job->delete($this->Job->id);
        $this->uses = array("Error");
        $this->Error->save(array("Error" => array("job_id" => $i, "error" => $errorsText)));
    }*/
}

}

?>

给出错误:

PHP Fatal error:  Class 'AppModel' not found in /home/webdev/webroot/Cake/lib/Cake/Utility/ClassRegistry.php on line 185

如果我试着改变这行

$this->uses = array("Job");

$this->uses = "Job";

我得到错误:

Notice Error: Undefined property: JobManagerShell::$Job in [/home/webdev/webroot/Vehicle_Scrapper/lib/Cake/Console/Shell.php, line 491]

我一直在努力寻找这个问题的答案,但我似乎找不到。

在你的shell脚本/文件中,可能在这里(src/shell/your-script-file)。(for cake-php 3.X)

在顶部使用this:

use Cake'Core'App;
use App'Controller'ReportsController; //(path to your controller).

并在initialize()函数下创建控制器对象

public function initialize() {
    parent::initialize();
    $this->reports = new ReportsController();
}

之后,您可以调用shell文件中的任何控制器函数。

例如,我有get_reports_details()函数在我的ReportsController,所以我将调用这个函数如下:

publict function main(){
 $this->reports->get_reports_details();
}

如果您需要使用其他模型,请使用:

$this->loadModel('ModelName')

阅读更多:loadModel in CakeBook

另外,我不建议在shell中使用控制器动作。使用模型方法代替。(如果你在模型中没有你需要的东西,把它们移到模型中[这是它们的位置])