[FuelPHP 1.7] Execute a task from a task

This is Kusakabe from the development team

First of all, when you are creating a FuelPHP task, have you ever thought about running a task from another task? I will explain that here

Run a task from a task

Let's say you have a task like this that displays sugoi when you run it:

taskone.php

<?php namespace Fuel\Tasks; class TaskOne { public static function run() { \Cli::write('sugoi'); return 0; } }

Let's consider executing this TaskOne from within another task.
We define the task that calls TaskOne as TheTask.

The directory structure is

 fuel
  └app
   └tasks
     ├taskone.php
     └thetask.php

Let's say it is

thetask.php

<?php namespace Fuel\Tasks; class TheTask { public static function run() { TaskOne::run(); return 0; } }

This works, doesn't it? Let's run TheTask

$ oil refine TheTask Fatal Error - Class 'Fuel\Tasks\TaskOne' not found in APPPATH/tasks/thetask.php on line 8

No, that's not possible. The TaskOne class could not be found.
I thought the autoloader would be able to load it since it's in the same namespace, but that wasn't the case. I have to manually instruct it to load.

Loading Tasks

All you need to do is load taskone.php

[Deprecated]

require_once '/path/fuel/app/tasks/taskone.php';

This way you can load the target file, but you probably want to avoid writing the file path directly in the source code.
Let's consider a way to dynamically obtain the path.
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; } }

Let's try running it

$ oil refine TheTask sugoi

It's done. That's it

Next time, we'll look at something a little more complicated: how to call a task in a module from within a task

If you found this article helpful,please give it a "Like"!
1
Loading...
1 vote, average: 1.00 / 11
3,686
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author