这里说的命令行程序就是在命令行(或者叫shell)下执行的程序, 因为我们多数时间是用浏览器来访问symfony程序的, 而有些时候, 我们也需要在shell下来执行我们的程序, 比如定时任务.
在网上一番搜索并没有找到相关内容, 在1.0的<The Definitive Guide To symfony>里提到了一个init-batch的命令, 但是这个命令在1.2中已经不存在了.
后来终于在symfony命令中发现了generate:task命令, 这个命令的帮助文档是这样写的.
语法:
symfony generate:task [--dir="..."] [--use-database="..."] [--brief-description="..."] task_name
参数:
task_name The task name (can contain namespace)
选项:
–dir The directory to create the task in (default: lib/task)
–use-database Whether the task needs model initialization to access database (default: propel)
–brief-description A brief task description (appears in task list)
描述:
The generate:task creates a new sfTask class based on the name passed as
argument:
./symfony generate:task namespace:name
The namespaceNameTask.class.php skeleton task is created under the lib/task/
directory. Note that the namespace is optional.
If you want to create the file in another directory (relative to the project
root folder), pass it in the –dir option. This directory will be created
if it does not already exist.
./symfony generate:task namespace:name –dir=plugins/myPlugin/lib/task
If you want the task to default to a connection other than propel, provide
the name of this connection with the –use-database option:
./symfony generate:task namespace:name –use-database=main
The –use-database option can also be used to disable database
initialization in the generated task:
./symfony generate:task namespace:name –use-database=false
You can also specify a description:
./symfony generate:task namespace:name –brief-description=”Does interesting things”
简单来说, 这个命令是用来创建命令行任务的, 我们来做一个简单的测试.
./symfony generate:task test
这样我们就生成了test命令, 我们可以象下面这样使用test命令
./symfony test
虽然什么也没有输出, 但是没有报错说明命令存在. 如果要给命令添加动作需要修改 /lib/task/testTask.class.php
我们写一个简单的例子
// add your code here
echo "it runing\n";
$users = UserPeer::doSelect(new Criteria);
echo count($users);
这段代码执行了数据库操作, 这说明在task中类都是自动在载的, 详细阅读testTask.class.php中的代码我们会发现task还支持很多功能, 设置参数, 命名空间等等.
(未完待续)