Reputation: 696
How can I load a model in ...\app\Config\Autoload.php?
Code:
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
class Autoload extends AutoloadConfig {
public function __construct() {
//load here
//i've tried,
$my_model = new \App\Models\My_model();
$my_model = model("App\Models\My_model");
}
Nothing is working.
What is the correct way?
Looking for help. Thanks in advance.
Upvotes: 2
Views: 3822
Reputation: 2162
This really depends on where you want to use this model. Autoloading does not work the same way as codeigniter 3 where everything would be put into the same super object.
If what you want is to use this model in a bunch of controllers then you can add that to your baseController in your initController function. Let's say you want to autoload the article model:
public $article;
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->article = new \App\Models\ArticleModel();
}
Now all your controllers that extend to your baseController can access this model with $this->article.
If what you want is to use the autoload and you can do that too, but not in a construct, for that you should use the classMap property.
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
*
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array
*/
public $classmap = [
'Article' => APPPATH . 'Models/ArticleModel.php'
];
But this option is more for classes that exist outside the normal codeigniter structure. So I would advise into using the first option.
Upvotes: 3