php - 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
我做错了什么导致我的库无法加载?
解决方案
在 CI4BaseController
中,您可以创建希望被多个其他控制器使用的东西。在 CI4 中创建扩展其他类非常容易。
在我看来,您唯一缺少的就是创建Template
课程。(还有其他一些小事,但我该指手画脚吗?)
一件大事可能只是你没有展示它,即使你在做它。那是使用namespace
和use
指令。它们是 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>
我知道我还没有完全创建您想要做的事情。但是以上内容应该可以让您到达您想去的地方。无论如何,我希望如此。
推荐阅读
- angularjs - 从角度传递到控制器的对象显示参数的空值?MVC
- terminology - 命名回调函数时“fcn”代表什么?
- elasticsearch - Elasticsearch 无痛查询以将日期字段值与用户输入的日期值进行比较
- angular - 在角度和firebase中注销时退订不起作用
- php - 如何在 guzzle 查询构建期间将“管道”添加到 get 参数中
- ios - 如何在 iOS 应用程序的 Mapbox 中将 GeoJSON 字典显示为热图
- angular - 为什么这个自定义验证器不起作用?
- python - 显示整个列表,用户可以与之交互
- android - 在 Android Room 中,如何创建和调用自定义查询
- angularjs - 我在这个自定义指令代码中遇到问题