PHPackages                             bonditka/yii2-task - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. bonditka/yii2-task

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

bonditka/yii2-task
==================

System of task.

v0.1(8y ago)010BSD-3-ClausePHP

Since Apr 10Pushed 8y ago1 watchersCompare

[ Source](https://github.com/bonditka/yii2-task)[ Packagist](https://packagist.org/packages/bonditka/yii2-task)[ RSS](/packages/bonditka-yii2-task/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (6)Versions (3)Used By (0)

Система задач Yii2
==================

[](#система-задач-yii2)

Добавляет функционал создания и выполнения произвольной задачи. В качестве задачи должен быть указан класс реализующий интрфейс `\bonditka\task\components\TaskInstance`.

В контексте данного расширения задача — это многошаговая операция. Шаги задачи описываются свойством `arStep` в реализации TaskInstance.

Задачи могут быть тегированы различными модулями, через соответствующее свойство `module`, что позволяется довольно гибко настраивать систему задач в соответствии со своими нуждами.

Установка
---------

[](#установка)

Предпочтительный вариант установки через [composer](http://getcomposer.org/download/).

Чтобы установить, выполните следующую команду:

```
php composer.phar require --prefer-dist bonditka/yii2-task "*"

```

или добавьте

```
"bonditka/yii2-task": "*"

```

в блок require вашего `composer.json` файла.

После чего необходимо применить миграции:

```
php yii migrate
```

Использование
-------------

[](#использование)

Пример запуска не выполненных задач по крону:

```
//crontask
$tasks = Task::getTaskToRun();
foreach($tasks as $task){
	do {
		$arResult = $task->run();

		if (!is_array($arResult) && helpers\ArrayHelper::keyExists('errors', $arResult)) {
			if(is_array($arResult['errors'])){
				$error = implode('. ', $arResult['errors']);
			}
			else{
				$error = $arResult['errors'];
			}
			throw new yii\base\ErrorException('Задача выполнилась с ошибками: '.$error);
		}

		if(!helpers\ArrayHelper::keyExists('progress', $arResult) || !helpers\ArrayHelper::keyExists('nextStep', $arResult)){
			throw new yii\base\ErrorException('Задача не вернула сигнала о завершении или переходе на следующий шаг');
		}

		$step = helpers\ArrayHelper::getValue($arResult, 'nextStep');
		$task->setStep($step)->taskSave();

	} while (!empty($arResult['nextStep']));
	$task->complete()->taskSave();
}
```

```
//TaskInstance
use yii\base as yiiBase;
use yii\helpers;

class TaskInstance extends yiiBase\Model implements \bonditka\task\components\TaskInstance
{
    public $step;

    public function rules()
    {
        return [
            [['step'], 'required'],
            [['step'], 'string'],
        ];
    }

    /** @var array of task step */
    public $arStep = [
        'first' => [
			'methodName' => 'myFirstAwesomeMethod',
			'message' => 'myAwesomeMethod is done. Next step is second',
		],
        'second' => [
			'methodName' => 'mySecondAwesomeMethod',
			'message' => 'myAwesomeMethod is done. Next step is third',
		],
        'third' => [
			'methodName' => 'myThirdAwesomeMethod',
			'message' => 'myAwesomeMethod is done. Task is done.',
		]
    ];

    /** @param array $arStep contains the steps of the task.
     *  Every step must contain
     *      'methodName' — the name of the method of the current instance of the class that is currently running,
     *      optional* 'message' — description of actions of the current step for the user
     */

    public function setSteps(array $arStep)
    {
        $this->arStep = $arStep;
    }

    public function getSteps(){
        return $this->arStep;
    }

    /**
     * @return integer between 0 and 100 of progress by current task
     */
    public function getProgress()
    {
        $stepPosition = array_search($this->step, array_keys($this->arStep));
        return ceil((($stepPosition + 1) / count($this->arStep)) * 100);
    }

    protected function getNextStep()
    {
        $keys = array_keys($this->arStep);
        return isset($keys[array_search($this->step, $keys) + 1]) ? $keys[array_search($this->step, $keys) + 1] : null;
    }

    /**
     * @param $param
     */
    protected function myFirstAwesomeMethod($param)
    {
        //do something...
        return true;
    }

    /**
     * @param $param
     */
    protected function mySecondAwesomeMethod($param)
    {
        //do something...
        return true;
    }

    /**
     * @param $param
     */
    protected function myThirdAwesomeMethod($param)
    {
        //do something...
        return true;
    }

    /**
     * @param $param
     * @return array $arResult
     * @throws yiiBase\ErrorException
     * @throws yiiBase\InvalidConfigException
	 * Основной метод пошагового выполнения задания
     */
    public function executeStep($param)
    {
        if (empty($this->arStep)) {
            throw new yiiBase\InvalidConfigException;
        }

        if (empty($this->step)) {
            reset($this->arStep);
            $this->step = key($this->arStep);
        }

        $methodResult = $this->{$this->arStep[$this->step]['methodName']}($param);

        if($methodResult === false){
            throw new yiiBase\ErrorException;
        }

        return [
            'progress' => $this->getProgress(),
            'nextStep' => $this->getNextStep(),
            'result' => $methodResult
        ];
    }
}
```

Тестирование
------------

[](#тестирование)

Для запуска тестирования необходимо указать подключение к тестовой БД в файле `.env`. Пример файла:

```
# ---------
YII_DEBUG   = true
YII_ENV     = dev

# Databases
# ---------
TEST_DB_DSN           = mysql:host=localhost;port=3306;dbname=testdb
TEST_DB_USERNAME      = testdbu
TEST_DB_PASSWORD      = testdbpsw
TEST_DB_TABLE_PREFIX  =

```

Далее необходимо применить миграции:

```
php tests/bin/yii migrate
```

После чего можно запускать тесты:

```
vendor/bin/codecept build
vendor/bin/codecept run
```

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

2997d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/14823173?v=4)[Ekaterina Sergeeva](/maintainers/bonditka)[@bonditka](https://github.com/bonditka)

---

Top Contributors

[![bonditka](https://avatars.githubusercontent.com/u/14823173?v=4)](https://github.com/bonditka "bonditka (3 commits)")

---

Tags

yii2extensiontask

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/bonditka-yii2-task/health.svg)

```
[![Health](https://phpackages.com/badges/bonditka-yii2-task/health.svg)](https://phpackages.com/packages/bonditka-yii2-task)
```

###  Alternatives

[vyants/yii2-daemon

Extension provides functionality for simple daemons creation and control

7760.0k](/packages/vyants-yii2-daemon)[dmstr/yii2-cookie-consent

Yii2 Cookie Consent Widget

1454.6k](/packages/dmstr-yii2-cookie-consent)[imanilchaudhari/yii2-currency-converter

This extension will help to find out current currency conversion rate.

1911.7k](/packages/imanilchaudhari-yii2-currency-converter)[richardfan1126/yii2-js-register

Yii2 widget to register JS into view

1358.5k7](/packages/richardfan1126-yii2-js-register)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
