首页 > 解决方案 > CodeIgniter 4:自动加载库

问题描述

我正在使用CodeIgniter 4的最新“主”分支

我有一个试图自动加载的库。实际上,我希望拥有“一个”index.php(具有元、基本的 html 结构等),通过它我可以通过“模板”库加载视图。

我的库文件:(~/app/Libraries/Template.php)

//class Template extends CI_Controller
class Template {

    /* This throws an error, but I will open up a separte thread for this
    public function __construct() {
        parent::__construct();
    }
    */

    public function render($view, $data = array()) {        
        $data['content_view'] = $view;  
        return view('layout/index', $data);     
    }

}

我还设置了一个控制器:

class Locations extends BaseController
{

    public function index()
    {
        return $this->template->render("locations/index", $view_data); 
        //return view('locations/index');
    }

    //--------------------------------------------------------------------

}

在 ~/app/Config/ 我添加了我的库

    $classmap = [
        'Template' => APPPATH .'/Libraries/Template.php'
    ];

我收到以下错误:

Call to a member function render() on null

我做错了什么导致我的库无法加载?

标签: phpautoloadcodeigniter-4

解决方案


在 CI4BaseController中,您可以创建希望被多个其他控制器使用的东西。在 CI4 中创建扩展其他类非常容易。

在我看来,您唯一缺少的就是创建Template课程。(还有其他一些小事,但我该指手画脚吗?)

一件大事可能只是你没有展示它,即使你在做它。那是使用namespaceuse指令。它们是 CI 4 的必做项目。

由于您放置了不需要的文件,因此应该删除以下内容。看看我是如何使用自动加载器已知的use导入的。namespace

$classmap = [
        'Template' => APPPATH .'/Libraries/Template.php'
    ];

一、BaseController

/app/Controllers/BaseController.php

<?php
namespace App\Controllers;

use CodeIgniter\Controller;
use App\Libraries\Template;

class BaseController extends Controller
{

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = [];

    protected $template;

    /**
     * Constructor.
     */
    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->template = new Template();
    }

}

/app/Controllers/Locations.php

class Locations extends BaseController
{
    public function index()
    {
        // set $viewData somehow
        $viewData['someVar'] = "By Magic!";
        return $this->template->render("locations/index", $viewData);
    }
}

/app/Libraries/Template.php

<?php namespace App\Libraries;

class Template
{
    public function render($view, $data = [])
    {
        return view($view, $data);
    }
}

/app/Views/locations/index.php

This works as if... <strong><?= $someVar; ?></strong>

我知道我还没有完全创建您想要做的事情。但是以上内容应该可以让您到达您想去的地方。无论如何,我希望如此。


推荐阅读