【问题标题】:How to load a model in Autoload file in CodeIgniter 4如何在 CodeIgniter 4 的 Autoload 文件中加载模型
【发布时间】:2021-04-11 20:39:25
【问题描述】:

如何在 ...\app\Config\Autoload.php 中加载模型?

代码:

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");
    } 

没有任何效果。

正确的方法是什么?

寻求帮助。 提前致谢。

【问题讨论】:

    标签: php codeigniter-4


    【解决方案1】:

    这真的取决于你想在哪里使用这个模型。自动加载的工作方式与 codeigniter 3 不同,其中所有内容都将放入同一个超级对象中。

    如果你想要在一堆控制器中使用这个模型,那么你可以在你的 initController 函数中将它添加到你的 baseController 中。假设您要自动加载文章模型:

    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();
    }
    

    现在,所有扩展至 baseController 的控制器都可以使用 $this->article 访问此模型。

    如果您想要使用自动加载并且您也可以这样做,但不是在构造中,那么您应该使用 classMap 属性。

     /**
     * -------------------------------------------------------------------
     * 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'
    ];
    

    但这个选项更适用于存在于正常 codeigniter 结构之外的类。所以我建议使用第一个选项。

    【讨论】:

    • 其实我想在Autoload类的__construct()中得到一个模型。我不想到处加载它。就在 __construct 函数中。
    • 为什么只需要该结构中的模型?
    • 我必须动态地将一些数据推送到 $psr4 变量中。这就是为什么我需要那里的模型。有没有其他方法可以做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 2020-09-17
    • 1970-01-01
    • 2018-03-01
    相关资源
    最近更新 更多