[FuelPHP 1.7] Run tasks from tasks
This is Kusakabe from the development team.
While creating a FuelPHP task, have you ever thought about executing a task from a task? I'll write a story about that.
Run task from task
Suppose there is a task that displays sugoi when executed, such as the following:
taskone.php
<?php namespace Fuel\Tasks; class TaskOne { public static function run() { \Cli::write('sugoi'); return 0; } }
Consider running this TaskOne from within another task.
Define the task that calls TaskOne as TheTask.
The directory structure is
fuel
└app
└tasks
├taskone.php
└thetask.php
Suppose that
thetask.php
<?php namespace Fuel\Tasks; class TheTask { public static function run() { TaskOne::run(); return 0; } }
Don't you think you can do this? Let's run TheTask.
$ oil refine TheTask Fatal Error - Class 'Fuel\Tasks\TaskOne' not found in APPPATH/tasks/thetask.php on line 8
No. TaskOne class not found.
Since they are classes in the same namespace, it would seem that the autoloader would take advantage of loading them, but that was not the case. You must instruct loading here.
Loading tasks
What we need to do is load taskone.php.
[Not recommended]
require_once '/path/fuel/app/tasks/taskone.php';
This way you can read the target file, but you want to avoid writing the file path directly in the source.
Think of a way to get the path dynamically.
Referring to the implementation of the Oil command (fuel/packages/oil/classes/command.php), you can do the following.
[Recommended]
<?php namespace Fuel\Tasks; class TheTask { public static function run() { # tasksディレクトリの中からTaskOneに対応するファイルを探し、そのパスを取得 $file = \Finder::search('tasks', strtolower('TaskOne')); # TaskOneのファイルをロード require_once $file; # TaskOneを実行 TaskOne::run(); return 0; } }
I'll try running it.
$ oil refine TheTask sugoi
It's done. That's all.
Next time, we'll consider something a little more complicated: how to call a task within a module from within a task.