Search code examples
yiischeduled-tasksconsole-applicationcron-task

Yii Console Application does not auto-import Model as web appliccation


Here is my console.php which is same as main.php

return array(
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
'name' => 'My Console Application',

// preloading 'log' component
'preload' => array('log'),

 // autoloading model and component classes
'import' => array(
        'application.models.*',
        'application.components.*',
        'application.extensions.*',
),

The web application has no problem access those functions. However, console application yields error

Fatal error: Call to undefined method Myfunction::get_all_recipients() 

An discussion of this problem is also found at

https://github.com/yiisoft/yii/issues/2344

Also tried suggestions

Yii Command Line Does Not Autoload Models

but it still does not import model classes.


Solution

  • The second solution should work, but sometimes I use another approach. In the console command itself add the following:

    Yii::import('application.models.YourModel');
    

    or

    Yii::import('application.models.Subfolder.YourModel');
    

    if it's located in subfolder for example;

    This should placed before your code is processed. This autoloads only models or classes that your need for current command.