Loading a model from a directory outside of APP in CI4

Viewed 16

I would like to load a model in Codeigniter 4 from a directory outside of the normal model directory I want to load it from /WorkFlowModels instead of /app/models

I have the following code

namespace App\Controllers;

use CodeIgniter\Config\Factories;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\CollectionModel;
use CodeIgniter\Controller;



class Workflow extends Controller {

  protected $Collection      = '';
  private   $ModelDir        = '../app/WorkFlowModels/';

  public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
  {
         parent::initController($request, $response, $logger);
         $this->Session = \Config\Services::session();
  }


  public function GetActions()
  {

  

    foreach(scandir($this->ModelDir) as $Model)
    {
        if($Model == '..' || $Model == '.')
          continue;

        //Remove .php extension
        $Model = pathinfo($Model, PATHINFO_FILENAME);


         new \WorkFlowModels\TestModel();
    }
   


  }

}

When I try and initialize it with new \WorkFlowModels\TestModel(); it throws an error of Class 'WorkFlowModels\TestModel' not found

This is what my model looks like at the moment

namespace \WorkFlowModels;

use App\Libraries\MongoDb;

class TestModel {

  private $Collection   = '';

  public function check()
  {
    echo 'testing';
  }
}
1 Answers

The answer to this question is to add a namespace to the /config/autoload.php. like this.

public $psr4 = [
        APP_NAMESPACE     => APPPATH, // For custom app namespace
        'Config'          => APPPATH . 'Config',
        'WorkFlowModels'  => APPPATH . 'WorkFlowModels',
    ];
Related