[FuelPHP 1.7] Run tasks from tasks

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 say we want to run TaskOne from within another task.
Let's 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

It doesn't work. The TaskOne class cannot be found.
Since it's a class in the same namespace, I thought the autoloader would be smart enough to load it, but that didn't happen. I had to tell it to load.

Loading Tasks

All you need to do is load taskone.php

[Deprecated]

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

This will allow you to load the desired file, but you probably want to avoid writing the file path directly in the source.
Let's think about how to get the path dynamically.
Referring to the Oil command implementation (fuel/packages/oil/classes/command.php), you can do it as follows:

[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,623
X facebook Hatena Bookmark pocket

The person who wrote this article

About the author