Integrating CLI PHP with CakePHP


Integrating CLI PHP with CakePHP

我有一个功能不错的CakePHP 1.3.11站点,我需要一个定期维护的CLI脚本来运行,所以我用PHP编写它。有什么方法可以让蛋糕友好的脚本吗?理想情况下,我可以使用Cake的函数和Cake的数据库模型,但是CLI需要数据库访问,其他就不多了。理想情况下,我希望将我的CLI代码包含在控制器中,并将数据源包含在模型中,这样我就可以像调用任何其他Cake函数一样调用该函数,但只能从CLI作为计划任务。

搜索CakePHP CLI,得到的大多是CakeBake和cron作业;这篇文章听起来很有帮助,但它是一个旧版本的蛋糕,需要一个修改版本的index.php。我不再确定如何更改文件以使其在新版本的cakePHP中工作。

如果重要的话,我在Windows上,但我有完全访问服务器的权限。我目前计划安排一个简单的cmd "php run.php"风格的脚本。

使用CakePHP的shell,您应该能够访问CakePHP应用程序的所有模型和控制器。

作为一个例子,我已经建立了一个简单的模型,控制器和shell脚本:

/app/模型/post.php

<?php
class Post extends AppModel {
    var $useTable = false;
}
?>

/app/controllers/posts_controller.php

<?php
class PostsController extends AppController {
var $name = 'Posts';
var $components = array('Security');
    function index() {
        return 'Index action';
    }
}
?>

/app/供应商/壳/post.php

<?php
App::import('Component', 'Email'); // Import EmailComponent to make it available
App::import('Core', 'Controller'); // Import Controller class to base our App's controllers off of
App::import('Controller', 'Posts'); // Import PostsController to make it available
App::import('Sanitize'); // Import Sanitize class to make it available
class PostShell extends Shell {
    var $uses = array('Post'); // Load Post model for access as $this->Post
    function startup() {
        $this->Email = new EmailComponent(); // Create EmailComponent object
        $this->Posts = new PostsController(); // Create PostsController object
        $this->Posts->constructClasses(); // Set up PostsController
        $this->Posts->Security->initialize(&$this->Posts); // Initialize component that's attached to PostsController. This is needed if you want to call PostsController actions that use this component
    }
    function main() {
        $this->out($this->Email->delivery); // Should echo 'mail' on the command line
        $this->out(Sanitize::html('<p>Hello</p>')); // Should echo &lt;p&gt;Hello&lt;/p&gt;  on the command line
        $this->out($this->Posts->index()); // Should echo 'Index action' on the command line
        var_dump(is_object($this->Posts->Security)); // Should echo 'true'
    }
}
?>

整个shell脚本在这里是为了演示您可以访问:

  1. 直接加载和不通过控制器加载的组件
  2. 控制器(首先导入Controller类,然后导入你自己的控制器)
  3. 控制器使用的组件(创建新控制器后,运行constructClasses()方法,然后运行特定组件的initialize()方法,如上所示)
  4. 核心实用程序类,如上面显示的消毒类。
  5. 模型(只包括在你的shell的$uses属性)。

你的shell可以有一个总是首先运行的启动方法,以及一个main方法,它是你的shell脚本的主进程,在启动后运行。

要运行此脚本,您将在命令行上输入/path/to/cake/core/console/cake post(可能必须检查在Windows上执行此操作的正确方法,该信息在CakePHP书中(http://book.cakephp.org)。

以上脚本的结果应该是:

mail
&lt;p&gt;Hello&lt;/p&gt;
Index action
bool(true)

这对我来说是有效的,但是也许那些在CakePHP shell中更高级的人可以提供更多的建议,或者可能纠正上面的一些…但是,我希望这足以让您开始。

从CakePHP 2开始,shell脚本现在应该保存到'Console'Command。在http://book.cakephp.org/2.0/en/console-and-shells.html

有很好的文档。