Search by

servidge / connector-codeigniter

shahidanwer

Connects a CodeIgniter 4 application to the LivingWeb core: embeds the assistant widget and syncs public content to the index.

Package info

github.com/shahidanwar/connector-codeigniter

pkg:composer/servidge/connector-codeigniter

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.1.0 2026-12-02 12:02 UTC

This package is auto-updated.

Last update: 2026-12-02 12:05:17 UTC


README

Connects a CodeIgniter 4 application (4.5+) to the Servidge core: embeds the assistant widget and keeps the application's public content in the index. Same job and same two public endpoints as the Laravel package; private data is never indexed and will be served through signed tool calls later (docs/decisions/0002).

Install

With Composer:

composer require servidge/connector-codeigniter

If the server can't reach Packagist, download servidge-connector-codeigniter.zip from your site's Install page in the Servidge portal, put it as it is (don't unzip it) in a packages folder in your app's root, and run composer config repositories.servidge artifact ./packages before composer require.

Without Composer, add the namespace to app/Config/Autoload.php:

public $psr4 = [
    APP_NAMESPACE        => APPPATH,
    'LivingWeb\CodeIgniter' => ROOTPATH.'vendor/servidge/connector-codeigniter/src',
];

CodeIgniter discovers the rest (the servidge:sync command, the servidgeClient/servidgeSyncer services and the servidge helper) from the namespace.

.env:

servidge.baseUrl      = 'https://servidge.com/livingweb'
servidge.keyId        = 'lw_k_...'   # connector key, from the portal's API keys page
servidge.secret       = 'lw_s_...'   # shown once when the key is created
servidge.siteId       = '01HX...'    # from the portal's Sites page
servidge.widgetKeyId  = 'lw_k_...'   # widget key, same page

Check the connection:

php spark servidge:sync --check

Upgrading from 1.0. The 1.0 names keep working: livingweb.* values in .env fill any setting with no servidge.* value, an existing app/Config/LivingWeb.php is used when there is no app/Config/Servidge.php, and livingweb_widget(), livingweb:sync, livingweb:tools:register, registerLivingWebEvents() and the livingwebClient/livingwebSyncer services still work.

Embed the widget

In your layout, before </body>:

<?php helper('servidge'); ?>
<?= servidge_widget(['title' => 'Ask us']) ?>

It prints one async script tag and nothing else; with no widget key configured it prints nothing, so a misconfigured deploy is just a normal site. Extra entries become data-livingweb-* attributes (title, placeholder, position); the locale defaults to the request's.

Index your content

Create app/Config/Servidge.php extending the package config and map each model to a mapper:

namespace Config;

class Servidge extends \LivingWeb\CodeIgniter\Config\Servidge
{
    public array $indexable = [
        \App\Models\PageModel::class => \App\Servidge\PageMapper::class,
    ];
}

A mapper yields the records, names them and decides what is public. Return null for anything that must not be indexed and it is removed from the index.

namespace App\Servidge;

use App\Models\PageModel;
use LivingWeb\CodeIgniter\Contracts\DocumentMapper;
use LivingWeb\CodeIgniter\Support\Sections;

final class PageMapper implements DocumentMapper
{
    public function records(): iterable
    {
        $model = new PageModel();
        for ($offset = 0; $rows = $model->withDeleted()->orderBy('id')->findAll(200, $offset); $offset += 200) {
            yield from $rows;
        }
    }

    public function externalId(mixed $page): string       { return 'page:'.$page['id']; }
    public function externalIdForKey(int|string $k): string { return 'page:'.$k; }

    public function toDocument(mixed $page): ?array
    {
        if (! $page['is_published'] || $page['deleted_at'] !== null) {
            return null;
        }

        return [
            'canonical_url' => site_url('pages/'.$page['slug']),
            'type'          => 'page',
            'title'         => $page['title'],
            'locale'        => 'en',
            'updated_at'    => date('c', strtotime($page['updated_at'])),
            'sections'      => Sections::fromHtml($page['body']),
        ];
    }
}

Records are whatever your model returns (arrays or entities). Sections::fromHtml() splits HTML at its headings into sections with stable ids; render the same HTML through Sections::withHeadingIds() on the page so the anchors the assistant cites exist. For plain text use Sections::single($text).

Push changes as they happen

Add the trait to the model:

use CodeIgniter\Model;
use LivingWeb\CodeIgniter\Models\IndexableModel;

class PageModel extends Model
{
    use IndexableModel;
    // ...
}

It registers afterInsert, afterUpdate and afterDelete callbacks that re-read the record and push it, or remove it when it is gone or soft-deleted. A failed push is logged (log_message('warning', …)) and never breaks the save. If the model has its own initialize(), call $this->registerServidgeEvents() from it. Updates made with a where() instead of ids cannot be attributed to records; the reconciliation catches those. Set servidge.observe = false to rely on the reconciliation alone.

Reconcile on a schedule

php spark servidge:sync

Walks every mapped model in batches of 100 upserts / 500 deletes and reports totals. Run it hourly from cron (or CodeIgniter's task scheduler).

Signed-in users and tools

Specified in packages/connector-contract/schema/identity.md and tools.md.

Identity. Point Config\Servidge::$identityResolver at a callable returning [subject, ['email' => …, 'name' => …]] for the signed-in user (or null); servidge_widget() then mints an identity token with your connector secret and puts it on the script tag. Or mint one yourself: servidge_identity_token($user->id, ['name' => $user->name]) and pass it as ['identity' => $token]. After a client-side login, LivingWeb.identify(token).

Tools. List them in Config\Servidge::$tools and register on deploy with php spark servidge:tools:register (--list shows what the core has). Each tool is a route protected by the VerifyToolRequest filter, which checks the core's signature and nonce and leaves the parsed call in VerifyToolRequest::$call:

// app/Config/Filters.php
public array $aliases = ['livingweb-tools' => \LivingWeb\CodeIgniter\Filters\VerifyToolRequest::class, /* … */];
// app/Config/Routes.php
$routes->post('servidge/tools/order_lookup', 'Tools::orderLookup', ['filter' => 'servidge-tools']);

// app/Controllers/Tools.php
public function orderLookup()
{
    $call = VerifyToolRequest::$call;
    $order = model(OrderModel::class)->where('customer_id', $call->subject())->find($call->argument('order_id'));
    if ($order === null) {
        return ToolResult::error('not_found', 'No such order on this account.');
    }

    return ToolResult::ok("Order {$order->id} was shipped on {$order->shipped_at}.", ['status' => $order->status], [['title' => "Order {$order->id}", 'url' => site_url("orders/{$order->id}")]]);
}

Your code authorises against $call->subject(); for a tool with requires_confirmation, $call->isConfirmed() is true and callId is the idempotency key.

How requests are signed

Every call carries an HMAC-SHA256 signature over the method, path, timestamp, a random nonce and the body hash, as specified in packages/connector-contract/schema/signing.md. RequestSigner is a byte-identical port of the Laravel implementation and is tested against the contract's shared vectors.

Tests

cd packages/codeigniter
../../apps/api/vendor/bin/phpunit     # signer vectors, sections

Verified end to end on CodeIgniter 4.7.5 (SQLite) against the core running locally, with the PageModel/PageMapper above: insert, update, unpublish, publish, soft delete and hard delete each produced the expected upsert or delete, drafts never left the app; livingweb:sync created 120 seeded pages in one run and reported them unchanged on the next; the widget on /pages/pricing answered with section focus from the injected heading ids.

CodeIgniter 3 is not supported; the existing CI3 apps would need a separate, smaller adapter (plain PHP signer plus a controller hook), which is cheap to add from RequestSigner and Sections if it is needed.