dgvirtual / codeigniter4-components
Codeigniter 4 Components library which allows creating custom HTML elements to use within view files
Package info
github.com/dgvirtual/codeigniter4-components
pkg:composer/dgvirtual/codeigniter4-components
Requires
- php: ^8.0
Requires (Dev)
- codeigniter4/devkit: ^1.0
- codeigniter4/framework: ^4.3
This package is auto-updated.
Last update: 2026-05-07 18:57:20 UTC
README
PHP library Components for Codeigniter 4 allows you to create custom HTML elements to use within your views. They allow to encapsulate html and css classes/styles into reusable website building blocks with the content and attributes of your choosing. They are written in regular PHP/CSS/HTML. Such custom HTML elements can include other HTML elements (custom or default).
Custom component tag always starts with x- (like
<x-button-green>Click Me!</x-button-green>).
To illustrate, with Components you write this in your view:
<x-button-green onclick="alert('I was clicked!')"> <?= $clickMeLabel ?> </x-button-green>
Which, is merged with the Component definition:
<button style="color: white; background-color: green;" <?= isset($onclick) ? 'onclick="' . $onclick . '"' : '' ?> > <?= $slot ?> </button>
And results in this in the browser:
<button style="color: white; background-color: green;" onclick="alert('I was clicked!')" > Click Me! </button>
Composer Installation
To install in an existing composer project, run in command line:
composer require dgvirtual/codeigniter4-components:dev-develop
Manual Installation
Let's say you want to put the library into the app/ThirdParty directory.
-
Download and unzip the code, copy the
codeigniter4-componentsfolder to theapp/ThirdPartydirectory. -
To enable Codeigniter to find the library, edit the
app/Config/Autoload.phpfile, add the Components library to the$psr4property:
public $psr4 = [ APP_NAMESPACE => APPPATH, 'Dgvirtual\Components' => APPPATH . 'ThirdParty/codeigniter4-components/src', // this line ];
Configuration
Edit the app/Config/View.php file. Add the following array element to the
$decorators property:
public array $decorators = [ 'Dgvirtual\Components\Libraries\ComponentDecorator', // this line ];
Try If It Works
To check if it works with the example components, put the string
<x-button-green>This should look like a button</x-button-green> in any of your
views and see if it renders as a button (if not, all you will see will be simple
text).
Now you can make some components of your own and put them in
app/Views/Components folder to make them usable in your app views.
How To Write and Use Components
Example components of all three types listed below are available in the
src/Components folder of the project. They can be used immediately.
Self-Closing Tag Components
At their most basic, components serve as dynamic templates that allow you to reduce the typing in your application. This can help boil longer, complex sections down to a single HTML tag. This is especially useful with CSS utility frameworks like TailWind, or when using the utilities in Bootstrap 5, etc. Using components in these situations allows you to keep the style info in one place where making changes to one file changes every instance of the view throughout the application.
To create a component, simply create a new view file within the
app\Views\Components directory or another place made accessible as described
in the installation step 4 above.
A simple avatar image component avatar.php might look something like this:
<img src="<?= $src ?? '' ?>" class="rounded-circle shadow-4" style="width: <?= $width ?? '150px' ?>;" alt="<?= $alt ?? '' ?>" />
When using the component within a view, you would insert a tag with x-
prepended to the filename:
<x-avatar src="<?= $userAvatarURL ?>" alt="<?= $userName ?>" />
Any attributes provided when you insert the component like this are made
available as variables within the component view. In this case, the $src and
$alt attributes are passed to the component view, resulting in the following
output:
<img src="http://example.com/avatars/foo.jpg" class="rounded-circle shadow-4" style="width: 150px" alt="John Smith" />
Components With Opening and Closing Tags
You can include the content within the opening and closing tags by inserting the
reserved $slot variable:
<x-button-green onclick="alert('I was clicked!')"> Click Me! </x-button-green>
The component button-green.php would look like this:
<button style="color: white; background-color: green;" <?= isset($onclick) ? 'onclick="' . $onclick . '"' : '' ?> type="<?= $type ?? 'submit' ?>" > <?= $slot ?> </button>
The rendered html would look like this:
<button style="color: white; background-color: green;" onclick="alert('I was clicked!')" type="submit" > Click Me! </button>
Controlled Components
Finally, you can create a class to add additional logic to the output. The file must be in the same directory as the component view and should have a name that is the PascalCase version of the filename, with 'Component' added to the end of it.
A famous-quotes component would have a view called famous-quotes.php and a
controlling class called FamousQuotesComponent.php. The class must extend
Dgvirtual\Component\Libraries\Component. The only requirement is that you
implement a method called render().
You would call it in one of the ways previously described.
See a usable basic example of famous-quotes component in the
src/Components folder.
It can be inserted into your project like this (self closing, no atributes):
<x-famous-quotes />
or self-closing tag with attributes:
<x-famous-quotes seconds="30" />
or a component with opening and closing tags:
<x-famous-quotes seconds="30">Famous Quotes</x-famous-quotes>
As you see, controlled components can include both the content via $slot and
html attributes.
Advanced Configuration
Review the src/Config/Components.php file. The default configuration specifies
that the app will search for component files in two locations:
public $componentsLookupPaths = [ // your local components APPPATH . 'Views/Components/', // example components __DIR__ . '/../Components/', ];
If you want the app to find components located elsewhere, copy this file to your
app/Config directory, change the namespace of the copy to namespace Config;,
and edit the $componentsLookupPaths to list all the locations where you want
the app to look for components. The project will then use this config instead of
the library's own.
Note: The first component found in the lookup paths will be used. Therefore, if you have custom components, list their paths first, and the default ones last.
Component Output Caching
By default every component re-renders on every request. For pages with many components, or for components that hit a database or an external API, you can enable output caching so that the rendered HTML is stored in CI4's cache service and returned immediately on subsequent requests.
How the cache key works
The renderer builds a deterministic cache key from:
- the component name
- the view file path and its last-modified time (so the cache automatically invalidates after you change the file and deploy)
- all tag attributes (including the
$slotcontent for paired-tag components) - an optional extra contributor from
Component::cacheKey()(see below)
Different attribute values produce different cache entries, so
<x-avatar src="a.jpg" /> and <x-avatar src="b.jpg" /> are cached
independently.
Caching view-only components (no class)
Set $viewCacheTtl in your app/Config/Components.php:
namespace Config; use Dgvirtual\Components\Config\Components as BaseComponents; class Components extends BaseComponents { public $componentsLookupPaths = [ APPPATH . 'Views/Components/', ]; /** * Cache all view-only components for 10 minutes. * Set to null (default) to disable. */ public ?int $viewCacheTtl = 600; }
This applies to every component that has no companion *Component.php class.
Components backed by a class are unaffected by this setting; they use
$cacheTtl on the class instead (see below).
Caching class-based components
Add the $cacheTtl property to your component class:
class AvatarComponent extends Component { /** * Cache the rendered HTML for 1 hour. * Null (default) means no renderer caching. */ public ?int $cacheTtl = 3600; }
Personalised components: adding extra cache-key contributors
If a component's output depends on something beyond its attributes — such as the
currently logged-in user — override cacheKey() so that different contexts
produce different cache entries:
class UserCardComponent extends Component { public ?int $cacheTtl = 300; public function cacheKey(): string { // One cache entry per user return (string) session('user_id'); } }
Without this, every user would receive the first user's cached HTML.
Important: know what your component renders
Before enabling caching, make sure you account for every input that influences the HTML output:
| Input source | Covered automatically? |
|---|---|
| Tag attributes | Yes |
$slot content |
Yes (it is part of attributes) |
| View file content | Yes (mtime-based) |
| Database / API calls | No — set a suitable TTL |
session() / logged-in user |
No — use cacheKey() |
$_SERVER, $_GET, etc. |
No — use cacheKey() |
When in doubt, leave $cacheTtl = null (the default) and let the component
manage its own caching internally (as the famous-quotes example does).
CI4 cache backend
The renderer uses CI4's cache() helper, which reads your application's
app/Config/Cache.php settings. Switching from file cache to Redis or Memcached
there automatically applies to component caching as well — no changes needed
here.
Credits
This project is an adaptation of Bonfire2 Component rendering functionality for general CodeIgniter 4 use. Bonfire2 was created by Lonnie Ezell lonnieje@gmail.com and contributors. For more information, visit the Bonfire2 project.
The adaptation and package was created by Donatas Glodenis. You can reach out to me at [dg@lapas.info] for any questions or feedback.
License
This project is licensed under the MIT License. See the LICENSE file for details.