将CLI PHP与CakePHP集成

Ben*_*cka 2 php cakephp command-line-interface cakephp-1.3

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

搜索CakePHP CLI主要是带来CakeBake和cron作业的结果; 这篇文章听起来非常有用,但它适用于旧版本的蛋糕,需要修改版本的index.php.我不再确定如何更改文件以使其在新版本的cakePHP中运行.

如果重要的话,我在Windows上,但我可以完全访问服务器.我目前正计划安排一个简单的cmd"php run.php"样式脚本.

mtn*_*rop 5

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

作为一个例子,我设置了一个简单的模型,控制器和shell脚本:

/app/models/post.php

<?php
class Post extends AppModel {
    var $useTable = false;
}
?>
Run Code Online (Sandbox Code Playgroud)

/app/controllers/posts_controller.php

<?php
class PostsController extends AppController {

var $name = 'Posts';
var $components = array('Security');

    function index() {
        return 'Index action';
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

/app/vendors/shells/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'
    }
}

?>
Run Code Online (Sandbox Code Playgroud)

整个shell脚本用于演示您可以访问:

  1. 直接加载但未通过控制器加载的组件
  2. 控制器(首先导入Controller类,然后导入自己的控制器)
  3. 控制器使用的组件(创建新控制器后,运行constructClasses()方法,然后运行特定组件的initialize()方法,如上所示.
  4. 核心实用程序类,如上面显示的Sanitize类.
  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)
Run Code Online (Sandbox Code Playgroud)

这对我有用,但也许那些在CakePHP shell中更先进的人可以提供更多的建议,或者可能更正上面的一些......但是,我希望这足以让你开始.