CodeIgniter4 基础
官网
https://codeigniter.org.cn/user_guide/database/queries.html
ci4有是轻量、快速和灵活的特点,不过想比较于tp,lavavel和其他框架尚有不足之处,比如参考文档相对较少,社区活跃度等,不过不影响phper使用。
基础安装
你可以从网站手动下载版本,但是对于本教程,我们将使用推荐的方法,通过 Composer 安装 AppStarter 包。 在命令行输入以下命令:
composer create-project codeigniter4/appstarter ci-news
问题集锦
1. 多模版共存时,调用$this->cachePage() 不区分域名,导致页面重复
解决:重写核心类
参考官网:https://codeigniter.org.cn/user_guide/extending/core_classes.html
解析:
- BaseService定义了可以重写的类
文件路径:vendor\codeigniter4\framework\system\Config\BaseService.php 中的codeigniter 方法 - Config/Service重定义加载自定义类
文件路径:app\Config\Services.php
添加如下
public static function codeigniter($config = null, $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('codeigniter');
}
return new \App\Libraries\CodeIgniter($config);
}
- 新建核心类文件
文件路径:app\Libraries\CodeIgniter.php
代码如下:
/**
* Generates the cache name to use for our full-page caching.
*/
protected function generateCacheName(Cache $config): string
{
if ($this->request instanceof CLIRequest) {
return md5($this->request->getPath());
}
$uri = clone $this->request->getUri();
$query = $config->cacheQueryString
? $uri->getQuery(is_array($config->cacheQueryString) ? ['only' => $config->cacheQueryString] : [])
: '';
return md5($_SERVER['SERVER_NAME'] . $uri->setFragment('')->setQuery($query));
}
/**
* Determines if a response has been cached for the given URI.
*
* @return false|ResponseInterface
*
* @throws Exception
*/
public function displayCache(Cache $config)
{
if(isset($_GET['clear']) && $_GET['clear'] == 'true'){
cache()->delete($this->generateCacheName($config));
}
if ($cachedResponse = cache()->get($this->generateCacheName($config))) {
$cachedResponse = unserialize($cachedResponse);
if (! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers'])) {
throw new Exception('Error unserializing page cache');
}
$headers = $cachedResponse['headers'];
$output = $cachedResponse['output'];
// Clear all default headers
foreach (array_keys($this->response->headers()) as $key) {
$this->response->removeHeader($key);
}
// Set cached headers
foreach ($headers as $name => $value) {
$this->response->setHeader($name, $value);
}
$this->totalTime = $this->benchmark->getElapsedTime('total_execution');
$output = $this->displayPerformanceMetrics($output);
$this->response->setBody($output);
return $this->response;
}
return false;
}
generateCacheName 方法中添加$_SERVER[‘SERVER_NAME’]唯一标识
displayCache方法中添加$_GET[‘clear’],方便前台删除时及时更新。