Search by

cosmira / yii1-strangler-proxy

tabuna

A Yii 1.1 filter for incremental JSON API migration with contract adaptation and legacy access checks.

Package info

github.com/cosmira/yii1-strangler-proxy

pkg:composer/cosmira/yii1-strangler-proxy

Statistics

Installs: 224

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0


README

Documentation for 9.7. Upgrading from 8.4.

Tests PHP 8.2–8.5 MIT license

Move Yii 1.1 API actions to a new backend without changing the existing client. Keep authentication, sessions, and access checks in Yii. One fluent filter forwards enabled actions and translates differences between the two API contracts. Unmapped actions and disabled features continue to run in Yii.

Requires PHP 8.2+ and Yii 1.1.31+. Supports JSON APIs, form-to-JSON mapping, and selected multipart uploads.

Installation

Install the package in your Yii application:

composer require cosmira/yii1-strangler-proxy:^9.7

Load Composer's vendor/autoload.php before the Yii bootstrap. Commit your application's composer.lock and use composer install for deployments.

Forward your first action

In your application's Yii configuration array, add params.strangler. This example uses an existing backend endpoint returning {"ID":42,"NAME":"Desk"}:

'params' => [
    'strangler' => [
        'base_uri' => 'https://backend.example',
        'features' => ['catalog' => false],
    ],
],

HTTPS certificates are verified by default. Protect the backend with a trusted channel before enabling the feature; the integration guide includes a server-owned token example.

Import the builder at the top of your existing controller file:

use Cosmira\Strangler\Strangler;

Append this entry to the array returned by filters(), after the existing security filters. Keep those entries and actionView() in place.

Strangler::proxy('catalog')
    ->get('view', '/api/items/{id}')
    ->build(),

The route verb selects the outgoing HTTP method. Use incoming: when an existing client submits a different verb. Keep authentication, method validation, CSRF and resource access in preceding Yii filters.

Forwarding skips the action and its lifecycle hooks. See access checks and cleanup.

First verify that direct backend calls without the trusted token fail, and that all Yii access checks run before Strangler. Then set params.strangler.features.catalog to the boolean true, reload your application's configuration and, with a permitted legacy session, request the existing API:

curl -i --cookie yii-session.txt 'https://legacy.example/index.php?r=catalog/view&id=42'

Expect the backend body {"ID":42,"NAME":"Desk"}, its status, and X-Strangler: 1. Set params.strangler.features.catalog to false and repeat: Yii should run actionView() instead. Use an HTTP(S) origin for base_uri, without a path, query, or credentials. Put the backend path in each route.

Configure each action where you declare it

Put settings for one endpoint in its configure: callback. Use singleResponse() for a JSON result that fits in one response, such as a search result with separate groups and contacts. Use asBinary() for photos, downloads, and other file responses.

use Cosmira\Strangler\RouteOptions;
use Cosmira\Strangler\Strangler;

Strangler::proxy('directory')
    ->requireForwarding()
    ->get(
        'search',
        '/api/directory/groups/tree/search',
        expects: 200,
        configure: static fn (RouteOptions $route) => $route->singleResponse(),
    )
    ->get(
        'image',
        '/api/directory/people/{person_id}/photo',
        expects: 200,
        configure: static fn (RouteOptions $route) => $route->asBinary(),
    )
    ->build();

singleResponse() skips automatic page collection and still applies JSON mapping. asBinary() skips default JSON success mapping so the file can stream. Use query() and errors() on either route. Use response() when a JSON endpoint needs its own response mapping.

Use requireForwarding() on a proxy whose declared actions belong to the backend while the feature is enabled. If forwarding would fall back to Yii before the first upstream request, the client receives HTTP 500 with strangler_native_fallback.

Read and save a JSON object

A catalog page reads and saves the same preferences. The browser sends JSON to Yii with POST. The backend replaces the preferences with PUT. Declare the fields once.

$path = '/api/catalogs/{catalogId}/preferences';

Strangler::proxy('catalog')
    ->mapQuery([])
    ->jsonFields([
        'caption' => 'string|null',
        'labels'  => 'list<string>',
        'listed'  => 'bool',
    ])
    ->get('preferences', $path)
    ->put('savePreferences', $path, incoming: 'POST')
    ->build();

With ?catalogId=summer, both actions use /api/catalogs/summer/preferences. The submitted JSON {"CAPTION":null,"LABELS":[],"LISTED":0} reaches the backend as {"caption":null,"labels":[],"listed":false}. A request missing LABELS stays in Yii. This mapping works on a controller without an Active Record model. See field types and responses.

Choose a route from the submitted form

One Yii PUT action edits a term's text or moves the term to another category. The URL contains the term's id and its source_category_id. Each supported form changes exactly one field.

use Cosmira\Strangler\Forward;

Strangler::proxy('catalog')
    ->uppercase('TERM_ID')
    ->select('edit', 'PUT', static function (array $form): ?Forward {
        $term = '/api/categories/{source_category_id}/terms/{id}';

        return match (array_keys($form)) {
            ['TEXT'] => Forward::put($term, payload: ['TEXT' => $form['TEXT']]),
            ['MOVE_TO'] => Forward::post($term . '/move', payload: ['CATEGORY_ID' => $form['MOVE_TO']]),
            default => null,
        };
    })
    ->build();

Submitting {"MOVE_TO":"legal"} sends one POST with {"category_id":"legal"}. Submitting both fields returns null from the selector and lets Yii handle the whole form. The selected destination inherits the action's shared mappings. Its prepared payload still uses the configured Yii-to-upstream naming and value conventions. Use Forward::get($path, configure: ...) when a selected read needs its own query or response mapping. The callback receives the same RouteOptions as a direct GET route. See reusing a prepared form when selection needs a database lookup.

Save one form through two REST endpoints

A catalog form submits its title and label IDs as JSON. The backend exposes the item and its labels separately. In the existing controller's filter, yield the requests in execution order. This example assumes preceding Yii filters have validated the ID, title and label IDs, and authorized both changes.

use Cosmira\Strangler\Strangler;
use Cosmira\Strangler\StranglerProxy;

Strangler::proxy('catalog')
    ->action('saveListing', 'POST', static function (StranglerProxy $api, array $query, array $form): \Generator {
        $id = (string) $query['id'];
        $item = '/api/items/' . rawurlencode($id);

        yield $api->write(
            'PATCH', $item, body: ['title' => $form['title']],
            confirm: static fn (mixed $receipt): bool => $receipt instanceof \stdClass
                && ($receipt->id ?? null) === $id,
        );
        yield $api->write('PUT', $item . '/labels', body: ['ids' => $form['label_ids']]);
    })
    ->build();

The labels request runs only when the title endpoint returns HTTP 200 and the same item ID in its receipt (for example, {"id":"42"}). On success the client receives the last response. If replacing the labels fails, the client receives that error and the title may already have changed. Choose this form of forwarding when the client can handle partial updates. See HTML form input, failures and readback.

Use Json::identifies('item_id', $id) as the write confirmation for a JSON receipt with the identifier inside data. For a write associated with a nested form row, yield Json::scopeValidationErrors($response, "labels.$index") to preserve that row's position in a 422 response.

Apply the controller contract to a composed action

Use Forward::guardedSequence() when a selected sequence must run the same native bypass and nested-write checks as a regular route. Register a model-based controller contract and declare which nested fields the action handles.

use Cosmira\Strangler\Forward;
use Cosmira\Strangler\Strangler;

Strangler::proxy('catalog')
    ->request(relations: ['labels'], actions: ['edit'])
    ->select('edit', 'PUT', fn () => Forward::guardedSequence($this->saveItemAndLabels(...)))
    ->build();

A form with another native relation stays in Yii before any backend call. With requireForwarding('edit'), the same rejection returns strangler_native_fallback. Use request(before: ...) for application checks that must run before the first write. If a choose() selector selects this action, the contract checks run on the original form after selection. Keep selectors free of writes.

When the APIs differ

The catalog examples use id and name under data.

Without a controller contract, uppercase() enables naming, query translation, and the Yii response envelope. Its argument names the native primary key:

use Cosmira\Strangler\Strangler;

Strangler::proxy('catalog')
    ->uppercase('ITEM_ID')
    ->fields(['name' => 'TITLE'])
    ->get('get', '/api/items')
    ->get('view', '/api/items/{id}')
    ->post('create', '/api/items')
    ->put('edit', '/api/items/{id}')
    ->delete('delete', '/api/items/{id}')
    ->build();

This convention expects backend records under data. For the view action, {"data":{"id":42,"name":"Desk"}} becomes {"state":"data","data":{"ITEM_ID":42,"TITLE":"Desk"}}. Lists also require meta.total. Ordinary response attributes become uppercase; input, filter, and sort names become lowercase. Describe only naming or structural differences. The proxy does not restrict names to the backend's supported fields.

fields() shares aliases across writes, responses, filters, ordering and validation field names. Use request(fields: [...]) or response(fields: [...]) for directional exceptions. A controller contract supplies the native error envelope; otherwise configure error mapping.

See API adaptation for body-to-route bindings, relations, request guards, and custom envelopes.

Connect existing REST controllers

If your controllers share a model accessor and a parsed request envelope, connect those existing methods once. Put this class where Composer or Yii can autoload it. This example assumes the controllers expose getModel() and data():

use Cosmira\Strangler\ControllerContract;

class ApiContract extends ControllerContract
{
    public function model(CController $controller): CActiveRecord
    {
        return $controller->getModel();
    }

    public function payload(CController $controller): array
    {
        return $controller->data();
    }
}

Register the contract once in the existing application configuration:

'params' => [
    'strangler' => [
        'controller_contract' => ApiContract::class,
    ],
],

Keep the other Strangler settings. Each controller declares only routes and resource-specific differences:

use Cosmira\Strangler\Strangler;

Strangler::proxy('catalog')
    ->get('view', '/api/items/{id}')
    ->build();

The configured contract enables naming, query, and response conventions. The package reads the native model's primary key when handling a selected request, after preceding Yii filters. Building the filter does not read the model. Conventional get, view, create, edit, and delete actions also check the incoming method and request shape. Authentication, permissions, CSRF, and application-specific rules remain in your existing Yii filters.

Shared names and value conversions belong in the same controller contract.

Reuse a related resource

Declare a resource's differences in its existing controller filter. Related records can reuse that declaration instead of repeating field maps or branching on record IDs:

return Strangler::proxy('catalog')
    ->response(relations: [
        'items' => ItemController::class,
        'owner' => ['controller' => PersonController::class, 'many' => false],
    ])
    ->get('view', '/api/catalogs/{id}')
    ->build();

Related controllers supply their own Strangler record declarations. Resolution is lazy and does not run actions or init(). See requirements and overrides.

Run the complete example

The catalog example runs Yii and a backend against one SQLite dataset. It requires pdo_sqlite:

git clone --branch 9.7.0 --depth 1 https://github.com/cosmira/yii1-strangler-proxy.git
cd yii1-strangler-proxy
composer install
composer example:verify

The verifier starts local servers, checks legacy and proxied contracts, and removes its temporary data. Success prints All catalog contracts passed. and a check count.

Before enabling a feature

Only boolean true enables a feature. Missing flags and unmapped actions stay in Yii. Disabling a flag changes routing; it does not undo backend writes.

The proxy sends X-User-Id and X-Strangler-Locale over your trusted channel. These headers do not grant resource permissions. Client Cookie and Authorization are not forwarded by default. Backend Set-Cookie headers are removed.

There are no retries or fallback to Yii after forwarding. A transport failure returns 503, even if the backend committed a write. Follow the operations guide for uncertain outcomes.

For uploads, use files() in the route's configure: callback. Large uploads require cURL for bounded PHP memory. See file performance for buffering limits and measurements.

Documentation

Guide What it covers
API adaptation Naming conventions, query and body differences, response graphs, and uploads.
Compatibility checklist Request guards, callback scope, related resources, and checks before enabling a feature.
Integration Security filters, trusted headers, configuration, callbacks, and development checks.
File performance Upload transport requirements, buffering, and reproducible measurements.
Operations Deployment, feature flags, diagnostics, rollback, and uncertain writes.
Runnable catalog A complete local migration with native and proxied actions.

For package development, follow the local checks. Report bugs or propose changes in GitHub issues.