2011-09-30 50 views
2

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

搜索CakePHP CLI主要是提供有关CakeBake和cron作业的结果; this article听起来非常有帮助,但它是一个老版本的蛋糕,需要修改版本的index.php。我不再确定如何更改文件以使其在CakePHP的新版本中工作。

我在Windows上,如果它很重要,但我有完全访问服务器。我目前正计划安排一个简单的cmd“php run.php”样式脚本。

回答

5

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

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

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

?> 

整个shell脚本是有证明你可以访问:您直接加载,并且通过控制器

  • 控制器(第一进口控制器类不加载

    1. 组件,然后导入您的自己的控制器)
    2. 控制器使用的组件(创建新控制器后,运行constructClasses()方法,然后运行特定组件的initialize()方法,如上所示。
    3. 核心实用程序类,如上面显示的Sanitize类。
    4. 模型(只包含在你的shell的$uses属性中)。

    你的shell可以有一个始终运行的启动方法,以及主要的方法,这是你的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的壳是更高级的可以提供更多的建议,或有可能纠正一些上述的......不过,我希望这是足以让你开始。