Version 4.5.0
Release Date: April 7, 2024
4.5.0 release of CodeIgniter4
Highlights
Update minimal PHP requirement to 8.1.
Update minimal PHPUnit requirement to 10.5.
CORS filter (contributed by kenjis) See Cross-Origin Resource Sharing (CORS).
The spark optimize command for performance improvement on production environment (contributed by kenjis). See spark optimize.
Enhancements
Required Filters
New Required Filters have been introduced. They are special filters that are applied before and after other kinds of filters, and always applied even if a route does not exist.
The following existing functionalities have been reimplemented as Required Filters.
The Benchmark Timers used by Debug Toolbar now collect Required Before Filters and Required After Filters data.
The benchmark points have been changed:
Before
bootstrap: Creating Request and Response objects, Eventpre_system, Instantiating RouteCollection object, Loading Routes files, Instantiating Router object,routing: Routing,
After
bootstrap: Creating Request and Response objects, Eventpre_system.required_before_filters: Instantiating Filters object, Running Required Before Filters.routing: Instantiating RouteCollection object, Loading Routes files, Instantiating Router object, Routing,
Routing
AutoRouting Improved: The
$translateUriToCamelCaseoption has been added that allows using CamelCase controller and method names. See Translate URI To CamelCase.- Others:
Added option
$multipleSegmentsOneParam. When this option is enabled, a placeholder that matches multiple segments, such as(:any), will be passed directly as it is to one parameter, even if it contains multiple segments. See Multiple URI Segments as One Parameter for details.Now the 404 controller’s method that you set in
$override404also receive aPageNotFoundExceptionmessage as the first parameter.Now you can use the
__invoke()method as the default method. See Default Method.
Commands
Added
spark optimizecommand to optimize configuration for production environment. See spark optimize for the details.Added
spark make:testcommand to generate a skeleton test file. See make:test for the details.Added
spark config:checkcommand to check Config values. See Confirming Config Values for the details.Added
spark phpini:checkcommand to check important PHP ini settings. See Checking PHP ini Settings for the details.Added
spark lang:findcommand to update translations keys. See Generating Translation Files via Command for the details.The
--dbgroupoption has been added to thespark db:tablecommand. See Database Commands.
Testing
DomParser: The new methods were added
seeXPath()anddontSeeXPath()which allows users to work directly with DOMXPath object, using complex expressions.CLI: The new
InputOutputclass was added and now you can write tests for commands more easily if you useMockInputOutput. See Using MockInputOutput.Fabricator: The Fabricator class now has the
setUnique(),setOptional()andsetValid()methods to allow calling of Faker’s modifiers on each field before faking their values.TestResponse: TestResponse no longer extends
PHPUnit\Framework\TestCaseas it is not a test. Assertions’ return types are now natively typedvoid.
Database
Query Builder
limit(0) Behavior
Added a feature flag
Feature::$limitZeroAsAllto fix the incorrect behavior oflimit(0).If
LIMIT 0is specified in a SQL statement, 0 records are returned. However, there is a bug in the Query Builder, and iflimit(0)is specified, the generated SQL statement will have noLIMITclause and all records will be returned.It is recommended that
$limitZeroAsAllin app/Config/Feature.php be set tofalseas this incorrect behavior will be fixed in a future version. See also findAll(0) Behavior.
Others
Added support for database names containing dots (
.).
Model
Model Field Casting
Added a feature to convert data retrieved from a database into the appropriate PHP type. See Model Field Casting for details.
findAll(0) Behavior
Added a feature flag
Feature::$limitZeroAsAllto fix the incorrect behavior oflimit(0)for Query Builder. See limit(0) Behavior for details.If you disable this flag, you need to change code like
findAll(0, $offset)tofindAll(null, $offset).
$updateOnlyChanged
Added a property $updateOnlyChanged whether to update
Entity’s only changed fields. If you set this property
to false, when you are updating an Entity, DataException
“There is no data to update” will not raise even if the values in the Entity have
not changed.
See Using CodeIgniter’s Model for details.
Saving Dates
Now you can configure the date/time format when you save Time instances. See Saving Dates for details.
Libraries
CORS: Added Cross-Origin Resource Sharing (CORS) filter and class.
- Validation:
Added the new rule
field_existsthat checks the filed exists in the data to be validated.The
$dbGroupparameter ofValidation::run()now accepts not only a database group name, but also a database connection instance or an array of database settings.
- Session:
RedisHandlernow can configure the interval time for acquiring locks ($lockRetryInterval) and the number of retries ($lockMaxRetries).Now you can use Redis ACL (username and password) with
RedisHandler. See RedisHandler Driver for details.
Security:
Config\Security::$redirectis now, by default, environment-specific. For production environment, changed totruebut is stillfalsefor other environments.
Others
Bootstrap: The
CodeIgniter\Bootclass has been introduced, replacing system/bootstrap.php.- Autoloader:
Autoloading performance when using Composer has been improved. Adding the
Appnamespace in theautoload.psr4setting in composer.json may also improve the performance of your app. See Application Namespace.FileLocator Caching implemented. See FileLocator Caching for details.
FileLocatorInterfacehas been added.
CodeIgniter: Added a pseudo-variable
{memory_usage}to show your memory usage in your view files, which was supported by CodeIgniter 3.Events: Added event points
pre_commandandpost_commandfor Spark commands. See Event Points.HTTP: Added
Message::addHeader()method to add another header with the same name. SeeCodeIgniter\HTTP\Message::addHeader().Web Page Caching:
ResponseCachehas been improved to include the request HTTP method in the cache key. This means that the same URI will be cached separately if the HTTP method is different.CSP: Added
ContentSecurityPolicy::clearDirective()method to clear existing CSP directives. See Clear Directives.
BREAKING
Behavior Changes
Lowercase HTTP Method Name
For historical reasons, the framework used HTTP method names in lower case like “get”, “post”. But the method token is case-sensitive because it might be used as a gateway to object-based systems with case-sensitive method names. By convention, standardized methods are defined in all-uppercase US-ASCII letters. See https://www.rfc-editor.org/rfc/rfc9110#name-overview.
Now the framework uses the correct HTTP method names like “GET”, “POST”.
Request::getMethod()returns uppercase HTTP methods.CURLRequest::request()does not change the accepted HTTP methods to uppercase.
See Lowercase HTTP Method Name for details.
Filter Execution Order
The order in which Controller Filters are executed has changed. See Upgrading Guide for details.
Nested Route Groups and Options
Due to a bug fix, the behavior has changed so that options passed to the outer
group() are merged with the options of the inner group().
See Upgrading Guide for details.
API\ResponseTrait
Now when a response format is JSON, if you pass string data, the framework returns a JSON response. In previous versions, it returned a HTML response. See Upgrading Guide for details.
Factories class
Factories has been changed to a final class. It is a static class, and even if it were extended, there is no way to replace it.
Others
AutoRouting Legacy: Changed so that a
PageNotFoundExceptionis thrown if the controller corresponding to the request URI does not exist.Logger: The
log_message()function and the logger methods inCodeIgniter\Log\Loggernow do not returnboolvalues. The return types have been fixed tovoidto follow the PSR-3 interface.Autoloader: The prefix
\in the fully qualified classname returned byFileLocator::findQualifiedNameFromPath()has been removed.BaseModel: The
getIdValue()method has been changed toabstract.Routing: The 404 Override feature does change the Response status code to 404 by default. See Upgrading Guide.
system/bootstrap.php: This file cannot be used. The code has been moved to the new
CodeIgniter\Bootclass.
Interface Changes
Note
As long as you have not extended the relevant CodeIgniter core classes or implemented these interfaces, all these changes are backward compatible and require no intervention.
ResponseInterface: The default value of the third parameter
$expireof theResponseInterface::setCookie()has been fixed from''to0.Logger: The psr/log package has been upgraded to v3.0.0.
Validation: The method signature of
ValidationInterface::run()has been changed. The?stringtypehint on the$dbGroupparameter was removed.
Method Signature Changes
FileLocatorInterface
Router: The first parameter of the
RouteCollectionconstructor has been changed fromFileLocatortoFileLocatorInterface.View: The third parameter of the
Viewconstructor has been changed fromFileLocatortoFileLocatorInterface.
Return Type Changes
Model: The return type of the
objectToRawArray()method in theModelandBaseModelclasses has been changed from?arraytoarray.
Traditional Validation Rules
To add declare(strict_types=1) to the framework codebase, the method parameter
type ?string for a value to validate in the all Traditional Validation rule
classes CodeIgniter\Validation\FormatRules and CodeIgniter\Validation\Rules
are removed.
For example, the method signature changed as follows:
Before: public function integer(?string $str = null): bool
After: public function integer($str = null): bool
Others
Logger: The method signatures of the methods in
CodeIgniter\Log\Loggerthat implements the PSR-3 interface have been fixed. Theboolreturn types are changed tovoid. The$messageparameters now havestring|Stringabletypes.Validation: The method signature of
Validation::run()has been changed. The?stringtypehint on the$dbGroupparameter was removed.
Removed Deprecated Items
Request
The
$upperparameter ingetMethod()inRequestInterfaceandRequesthas been removed. See Lowercase HTTP Method Name.The deprecated
isValidIP()method inRequestInterfaceandRequesthas been removed.The visibility of the deprecated properties
$uriand$configinIncomingRequesthas been changed to protected.The
$enableCSRFproperty inIncomingRequesthas been removed.The
removeRelativeDirectory()method inIncomingRequesthas been removed.The
$proxyIPsproperty inRequesthas been removed.
Filters
The following deprecated items have been removed, because now Multiple Filters are always enabled.
Filters::enableFilter()RouteCollection::getFilterForRoute()Router::$filterInfoRouter::getFilter()
Database
ModelFactory
Model
BaseModel::idValue()BaseModel::fillPlaceholders()Model::idValue()Model::classToArray()
Response
The visibility of the deprecated property
ResponseTrait::$CSPhas been changed to protected.The following deprecated properties have been removed.
ResponseTrait::$CSPEnabledResponseTrait::$cookiePrefixResponseTrait::$cookieDomainResponseTrait::$cookiePathResponseTrait::$cookieSecureResponseTrait::$cookieHTTPOnlyResponseTrait::$cookieSameSiteResponseTrait::$cookies
Security
SecurityInterface::isExpired()Security::isExpired()Security::CSRFVerify()Security::getCSRFHash()Security::getCSRFTokenName()Security::sendCookie()Security::doSendCookie()
CodeIgniter
$path$useSafeOutputuseSafeOutput()setPath()
Test
CIDatabaseTestCaseControllerResponseControllerTesterFeatureResponseFeatureTestCaseMock\MockSecurityConfig
Spark Commands
migrate:createsession:migration
Others
Cache: The deprecated
CodeIgniter\Cache\Exceptions\ExceptionInterfacehas been removed.- Config:
The deprecated
CodeIgniter\Config\Configclass has been removed.The deprecated
CodeIgniter\Config\BaseService::discoverServices()method has been removed.
Controller: The deprecated
Controller::loadHelpers()method has been removed.Exceptions: The deprecated
CodeIgniter\Exceptions\CastExceptionclass has been removed.Entity: The deprecated
CodeIgniter\Entityclass has been removed. UseCodeIgniter\Entity\Entityinstead.spark: The deprecated constant
SPARKEDhas been removed.
Message Changes
Added
CLI.generator.className.testmessage.Added
Validation.field_existserror message.
Changes
Bootstrap: The loading of .env and defining
ENVIRONMENThave been moved before loading of bootstrap.php.- Config:
Config\Feature::$multipleFiltershas been removed, because now Multiple Filters are always enabled.The default error level in the production environment (app/Config/Boot/production.php) has been changed to
E_ALL & ~E_DEPRECATEDto match the default php.ini for production.
RouteCollection: The HTTP method keys in the protected property
$routeshas been fixed from lowercase to uppercase.Exceptions: Unused
CodeIgniter\Exceptions\AlertErrorandCodeIgniter\Exceptions\EmergencyErrorwere removed.Forge:
SQLSRVForge now convertsENUMdata types toVARCHAR(n)when you add table columns. In previous version, it converted toTEXTthat is deprecated in SQL Server.declare(strict_types=1)has been added to most framework codebase.
Deprecations
Services: The
BaseService::$servicesproperty has been deprecated. No longer used.- CodeIgniter:
The
determinePath()method has been deprecated. No longer used.The
resolvePlatformExtensions()method has been deprecated. No longer used. It has been moved to theCodeIgniter\Boot::checkMissingExtensions()method.The
bootstrapEnvironment()method has been deprecated. No longer used. It has been moved to theCodeIgniter\Boot::loadEnvironmentBootstrap()method.The
initializeKint()method has been deprecated. No longer used. It has been moved to theAutoloader.The
autoloadKint()method has been deprecated. No longer used. It has been moved to theAutoloader.The
configureKint()method has been deprecated. No longer used. It has been moved to theAutoloader.
Response: The constructor parameter
$confighas been deprecated. No longer used.- Filters:
The feature that
Filtersaccept the lowercase HTTP method keys ofConfig\Filters::$methodshas been deprecated. Use correct uppercase HTTP method keys instead.The feature that the
spark filter:checkcommand accepts the lowercase HTTP method has been deprecated. Use correct uppercase HTTP method instead.
RouteCollection: The feature that the
match()andsetHTTPVerb()methods accept the lowercase HTTP methods has been deprecated. Use correct uppercase HTTP methods instead.FeatureTestTrait: The feature that the
call()andwithRoutes()methods accept the lowercase HTTP methods has been deprecated. Use correct uppercase HTTP methods instead.Database: The
BaseConnection::$strictOnhas been deprecated. It will be moved toMySQLi\Connectionin the future.
Bugs Fixed
See the repo’s CHANGELOG.md for a complete list of bugs fixed.